Problem 395371 · medium · Phase 03 Linear Management & Searching

Richest Fixed-Size Block

2D prefix sums · sliding rectangle · maximum

grid[r][c] is the ore content of one cell of a mining map. A survey block is exactly h rows tall and w columns wide and must lie fully inside the map. Return the largest total ore content of any such block. It is guaranteed that h <= rows and w <= cols.

Examples

Input:  grid = [[1, -2, 3], [4, 5, -6], [-7, 8, 9]], h = 2, w = 2
Output: 16
Explanation: the bottom-right block 5 + (-6) + 8 + 9 = 16 beats the other three blocks (8, 0, 10).

Input:  grid = [[2, 3]], h = 1, w = 1
Output: 3

Constraints

  • 1 <= rows, cols <= 300, 1 <= h <= rows, 1 <= w <= cols
  • -1000 <= grid[r][c] <= 1000
  • Target complexity: O(rows * cols). Summing every block cell by cell is too slow for the largest tests.

Goals

  • Reuse a summed-area table to score every candidate block in O(1)
  • Enumerate all top-left corners without running off the grid
Starting Python…