Maximum Sum of an Hourglass - Problem
You are given an m x n integer matrix grid.
We define an hourglass as a part of the matrix with the following form:
a b c
d
e f g
Return the maximum sum of the elements of an hourglass.
Note: An hourglass cannot be rotated and must be entirely contained within the matrix.
Input & Output
Example 1 — Basic 3x4 Matrix
$
Input:
grid = [[7,4,0,1],[1,9,6,2],[0,3,3,1]]
›
Output:
26
💡 Note:
The hourglass with maximum sum is at position (0,0): 7+4+0 (top) + 9 (middle) + 0+3+3 (bottom) = 26
Example 2 — Minimum 3x3 Matrix
$
Input:
grid = [[1,1,1],[1,1,1],[1,1,1]]
›
Output:
7
💡 Note:
Only one possible hourglass: 1+1+1 (top) + 1 (middle) + 1+1+1 (bottom) = 7
Example 3 — Negative Numbers
$
Input:
grid = [[-1,-2,-3],[-4,5,-6],[-7,-8,-9]]
›
Output:
-25
💡 Note:
Only one hourglass possible: (-1)+(-2)+(-3)+5+(-7)+(-8)+(-9) = -25
Constraints
- m == grid.length
- n == grid[i].length
- 3 ≤ m, n ≤ 150
- 0 ≤ grid[i][j] ≤ 106
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code