Problem 248641 · medium · Phase 02 Linear Data Structures

Best Hourglass

2d-lists · shapes · nested-loops

An hourglass in a grid is a group of seven cells shaped like this, anchored at some top-left cell:

a b c
  d
e f g

Given a grid of integers grid with at least 3 rows and 3 columns, return the largest sum of any hourglass that fits entirely inside the grid.

Examples

Input:  grid = [[1, 1, 1, 0],
                [0, 1, 0, 0],
                [1, 1, 1, 0],
                [0, 0, 0, 0]]
Output: 7
Explanation: the hourglass in the top-left corner sums 1+1+1 + 1 + 1+1+1.

Input:  grid = [[-1, -1, -1],
                [-1, -9, -1],
                [-1, -1, -1]]
Output: -15

Constraints

  • 3 <= rows, cols <= 100, -100 <= grid[r][c] <= 100

Goals

  • Sum a fixed non-rectangular shape at every valid position
  • Track a maximum that may be negative
Starting Python…