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
Maximum Sum of an Hourglass INPUT 3x4 Integer Matrix Grid 7 4 0 1 1 9 6 2 0 3 3 1 Hourglass Pattern: a b c d e f g Sum = a+b+c+d+e+f+g ALGORITHM STEPS 1 Initialize max_sum Set to minimum value 2 Iterate through grid i: 0 to m-3, j: 0 to n-3 3 Calculate hourglass sum Top row + middle + bottom sum = grid[i][j] + grid[i][j+1] + grid[i][j+2] + grid[i+1][j+1] + grid[i+2][j] + grid[i+2][j+1] + grid[i+2][j+2] 4 Update maximum max_sum = max(max_sum, sum) Time: O(m*n) | Space: O(1) FINAL RESULT Maximum Hourglass Found: 7 4 0 1 1 9 6 2 0 3 3 1 Calculation: Top: 7 + 4 + 0 = 11 Middle: 9 = 9 Bottom: 0 + 3 + 3 = 6 Total: 11 + 9 + 6 = 26 Maximum Sum: 30 (at position i=0, j=1) Key Insight: Single Pass Optimized: We only need to check positions where a complete hourglass fits (i from 0 to m-3, j from 0 to n-3). For each valid position, calculate the 7-element sum directly and track the maximum. No extra space needed - just constant variables for sum and max tracking. O(m*n) time, O(1) space. TutorialsPoint - Maximum Sum of an Hourglass | Single Pass Optimized Approach
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