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
Maximum Sum of an Hourglass ProblemInput Matrix740119620331Hourglass Patterna b c de f gSum = a+b+c+d+e+f+gCalculation7 + 4 + 0+ 9+ 0 + 3 + 3= 26Blue cells = Hourglass pattern, Red cell = CenterFind the hourglass with maximum sum
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
Asked in
HackerRank 25 Microsoft 15
25.8K Views
Medium Frequency
~15 min Avg. Time
890 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