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
6212928Hourglass Template:โ–  โ–  โ–  โ† Top row (sum) โ–  โ† Middle elementโ–  โ–  โ–  โ† Bottom row (sum)Current Sum: 6+2+1+2+9+2+8 = 30
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).
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
28.5K Views
Medium Frequency
~12 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen