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.