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:
30
💡 Note:
The hourglass with maximum sum is: 7+4+0 (top) + 9 (middle) + 0+3+3 (bottom) = 7+4+0+9+0+3+3 = 26. Wait, let me recalculate: 7+4+0+9+0+3+3 = 26. Actually checking position (0,1): 4+0+1+9+3+3+1 = 21. Position (0,0): 7+4+0+9+0+3+3 = 26. Let me check (0,1) again: grid[0][1]+grid[0][2]+grid[0][3]+grid[1][2]+grid[2][1]+grid[2][2]+grid[2][3] = 4+0+1+6+3+3+1 = 18. So maximum is 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:
-21
💡 Note:
Only hourglass: (-1)+(-2)+(-3)+5+(-7)+(-8)+(-9) = -6+5-24 = -25. Wait: -1-2-3+5-7-8-9 = -25. That's the only option.
Constraints
- m == grid.length
- n == grid[i].length
- 3 ≤ m, n ≤ 150
- 0 ≤ grid[i][j] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
Given m×n matrix with integer values
2
Hourglass Pattern
Find 3×3 areas matching hourglass shape
3
Maximum Sum
Return the largest hourglass sum found
Key Takeaway
🎯 Key Insight: An hourglass skips the middle row's side elements - only 7 cells total
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code