Maximum Sum of an Hourglass - Problem
You are given an m ร n integer matrix grid. Your task is to find the maximum sum of elements that form an "hourglass" pattern within the matrix.
An hourglass is a specific 3ร3 pattern that looks like this:
a b c
d
e f g
The hourglass consists of:
- Top row: 3 consecutive elements
- Middle: 1 element directly below the center of top row
- Bottom row: 3 consecutive elements directly below the middle element
Important constraints:
- The hourglass cannot be rotated
- The entire hourglass must fit within the matrix boundaries
- You need to find the hourglass with the maximum sum of its 7 elements
Goal: Return the maximum possible sum among all valid hourglasses in the matrix.
Input & Output
example_1.py โ Python
$
Input:
grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]]
โบ
Output:
30
๐ก Note:
The maximum hourglass sum is 30. One such hourglass is: 6+1+3+2+9+8+7 = 30 (starting at position [0,1])
example_2.py โ Python
$
Input:
grid = [[1,2,3],[4,5,6],[7,8,9]]
โบ
Output:
35
๐ก Note:
Only one hourglass is possible in a 3ร3 grid: 1+2+3+5+7+8+9 = 35
example_3.py โ Python
$
Input:
grid = [[-1,-2,-3,-4],[-5,-6,-7,-8],[-9,-10,-11,-12],[-13,-14,-15,-16]]
โบ
Output:
-48
๐ก Note:
With all negative numbers, we want the hourglass with values closest to zero. The maximum sum is -1+(-2)+(-3)+(-6)+(-9)+(-10)+(-11) = -42
Constraints
- m == grid.length
- n == grid[i].length
- 3 โค m, n โค 150
- 0 โค grid[i][j] โค 106
- The matrix must be large enough to contain at least one hourglass (minimum 3ร3)
Visualization
Tap to expand
Understanding the Visualization
1
Position the Template
Place the hourglass template at each valid 3ร3 position starting from top-left
2
Calculate Collection Value
Sum up the values of the 7 gems that align with the hourglass shape
3
Track Best Position
Remember the position that gives the highest total value
4
Move to Next Position
Slide the template to the next valid position and repeat
Key Takeaway
๐ฏ Key Insight: We must systematically check every valid 3ร3 position in the matrix, but only sum the 7 specific elements that form the hourglass pattern (skipping the corners of the 3ร3 square).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code