Ad platform~35 min2s · 256 MBtarget O(R^2 * C^2) time, O(C) spaceclassic twin: lc-363prefix-sums
An ad team keeps a grid of net results. Each row is a placement on a page and each place in a row is an hour of the day. A cell is the profit or the loss of one ad, and a loss is negative.
A budget review picks a block of neighbouring placements and neighbouring hours: a rectangle of the grid. The review wants the block with the largest total that does not pass a cap set by finance.
The cap is never below the smallest cell, so at least one single cell fits. A grid has up to 40 placements and 300 hours.
Write best_block_sum(grid, cap).
grid[r][c] is the net result of placement r in hour c. All rows have the same length.top ≤ r ≤ bottom and left ≤ c ≤ right, for any top ≤ bottom and left ≤ right.cap. At least one block always fits.Input: grid = [[1, 0, 1], [0, -2, 3]], cap = 2
Output: 2For each pair of rows, the column totals form one row. The best run of columns that stays at most 2 is shown.
| Rows | Column totals | Best run sum |
|---|---|---|
| 0 to 0 | [1, 0, 1] | 2 |
| 0 to 1 | [1, -2, 4] | 2 |
| 1 to 1 | [0, -2, 3] | 1 |
The largest of these is 2.
Input: grid = [[5]], cap = 5
Output: 5The only block is the single cell, and it is equal to the cap.
Input: grid = [[7, 8], [9, 10]], cap = 7
Output: 7Only the cell 7 fits under the cap.
1 ≤ grid.length ≤ 40 (placements)1 ≤ grid[r].length ≤ 300 (hours, the same for every row)-1,000,000 ≤ grid[r][c] ≤ 1,000,000 (net result of one ad)-1,000,000 ≤ cap ≤ 100,000,000,000, and cap is at least the smallest cell of the gridThere are 37,023,000 blocks. Checking each with a prefix table costs one step per block, which is already slow.
Fix a pair of rows (820 pairs) and add the rows up. Each block is then a run of one row of 300 totals. Sums reach 12,000,000,000 for the whole grid, so use 64-bit integers.