Maximum Sum of an Hourglass Problem
#2428
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2428.
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.lengthn == grid[i].length3 <= m, n <= 1500 <= grid[i][j] <= 10^6
Solution
Approach: Enumeration
An hourglass is a 3 x 3 block without the left and right cells of its middle row. Try every possible center (i, j) that has a full block around it, sum the nine cells, subtract the two removed ones, and keep the maximum.
Complexity: The time complexity is O(mn) and the space complexity is O(1), where m and n are the numbers of rows and columns.
class Solution:
def maxSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
ans = 0
for i in range(1, m - 1):
for j in range(1, n - 1):
s = -grid[i][j - 1] - grid[i][j + 1]
s += sum(
grid[x][y] for x in range(i - 1, i + 2) for y in range(j - 1, j + 2)
)
ans = max(ans, s)
return ans