Problem 236928 · medium · Phase 02 Linear Data Structures

Richest k x k Window

2d-lists · windows · nested-loops

Given a grid of integers grid and an integer k, return the largest possible sum of a k x k sub-grid (a block of k consecutive rows and k consecutive columns).

Examples

Input:  grid = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]], k = 2
Output: 28
Explanation: the bottom-right block 5 + 6 + 8 + 9 is the largest.

Input:  grid = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]], k = 3
Output: 45

Input:  grid = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]], k = 1
Output: 9

Constraints

  • 1 <= k <= min(rows, cols) <= 60, -1000 <= grid[r][c] <= 1000

Goals

  • Enumerate all k x k sub-grids of a larger grid
  • Sum a rectangular region and track the best
Starting Python…