← Back to index
MediumTypeScript3 min read

Maximum Sum of an Hourglass

Sliding a fixed hourglass mask through the grid and tracking the best sum with constant-time updates.

arraysprefix-sumgrid

Problem link

View on LeetCode

Solutions in this repo

  • TypeScript../maximum-sum-of-an-hourglass/solution.tsTypeScript solution

Hourglasses fit inside the grid only when every interior cell touches the mask. That means we just iterate all top-left anchors except the last two rows and columns and evaluate the sum of the fixed seven cells that make the hourglass.

The trick is to keep a running sum for each candidate instead of recomputing from scratch. I subtract the leftmost column of the previous hourglass, add the rightmost column, and adjust the lone middle cell per step.

Complexity

There are (m - 2) × (n - 2) possible hourglass anchors. Each update is O(1), so the whole sweep stays O(mn) time and O(1) space.

Pitfalls

  • Watch the boundary indices carefully—hourglasses fail when the grid is smaller than 3×3.
  • Reset the rolling sum only when shifting to a new row; horizontal moves can reuse most of the work.