Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Maximum Sum of an Hourglass

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2428" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given an m x n integer matrix grid. We define an hourglass as a part of the matrix with the following form: Return the maximum sum of the elements of an hourglass. Note that an hourglass cannot be rotated and must be entirely contained within the matrix. Example 1: Input: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]] Output: 30 Explanation: The cells shown above represent the hourglass with the maximum sum: 6 + 2 + 1 + 2 + 9 + 2 + 8 = 30. Example 2: Input: grid = [[1,2,3],[4,5,6],[7,8,9]] Output: 35 Explanation: There is only one hourglass in the matrix, with the sum: 1 + 2 + 3 + 5 + 7 + 8 + 9 = 35. Constraints: m == grid.length n == grid[i].length 3 <= m, n <= 150 0 <= grid[i][j] <= 106

Explanation

Here's the breakdown of the solution:

  • Iterate through possible hourglass centers: Loop through the matrix, considering each cell as the potential center of an hourglass. The loops will have limits to ensure the hourglass remains within the grid boundaries.
  • Calculate the hourglass sum efficiently: For each center, directly calculate the sum of the 7 elements that form the hourglass.
  • Track the maximum sum: Maintain a variable to store the maximum hourglass sum found so far and update it whenever a larger sum is encountered.

  • Runtime Complexity: O(m*n), Storage Complexity: O(1)

Code

    def max_hourglass_sum(grid):
    """
    Finds the maximum sum of an hourglass in a given grid.

    Args:
        grid: A 2D list of integers representing the grid.

    Returns:
        The maximum hourglass sum.
    """

    rows = len(grid)
    cols = len(grid[0])

    max_sum = float('-inf')  # Initialize with negative infinity

    for i in range(1, rows - 1):
        for j in range(1, cols - 1):
            # Calculate the hourglass sum
            current_sum = (
                grid[i - 1][j - 1]
                + grid[i - 1][j]
                + grid[i - 1][j + 1]
                + grid[i][j]
                + grid[i + 1][j - 1]
                + grid[i + 1][j]
                + grid[i + 1][j + 1]
            )

            max_sum = max(max_sum, current_sum)

    return max_sum

More from this blog

C

Chatmagic blog

2894 posts