Maps app~20 min2s · 256 MBtarget O(rows × columns + q) time, O(rows × columns) spaceclassic twin: lc-304prefix-sums
A maps app divides a city into square blocks. For each block, the app knows the revenue of the shops in it, in units.
A planner draws a rectangle on the map and wants the total revenue of every block inside it, edges included. Planners draw many rectangles in a row on the same map, and the revenue numbers do not change while they work.
The map can have 1,000 rows and 1,000 columns, and a planner can draw 100,000 rectangles.
Write rectangle_totals(grid, rectangles).
grid[r][c] is the revenue of the block in row r and column c. All rows have the same length.rectangles[j] is [top, left, bottom, right] with top <= bottom and left <= right. It covers rows top to bottom and columns left to right, all included.Input: grid = [[4, 2, 7], [1, 5, 3], [6, 8, 2], [9, 1, 4]], rectangles = [[1, 0, 2, 1], [0, 0, 3, 2], [2, 2, 2, 2]]
Output: [20, 52, 2]The table has 5 rows and 4 columns, with a border of zeros.
| Rectangle | Corners used | Total |
|---|---|---|
| [1, 0, 2, 1] | 26 - 6 - 0 + 0 | 20 |
| [0, 0, 3, 2] | 52 - 0 - 0 + 0 | 52 |
| [2, 2, 2, 2] | 38 - 22 - 26 + 12 | 2 |
The table is [[0, 0, 0, 0], [0, 4, 6, 13], [0, 5, 12, 22], [0, 11, 26, 38], [0, 20, 36, 52]].
Input: grid = [[5]], rectangles = [[0, 0, 0, 0]]
Output: [5]One block.
Input: grid = [[1, 2, 3]], rectangles = [[0, 1, 0, 2], [0, 0, 0, 0]]
Output: [5, 1]A map of one row.
1 ≤ grid.length ≤ 1,000 and 1 ≤ grid[r].length ≤ 1,0000 ≤ grid[r][c] ≤ 1,000,000 (revenue of one block)1 ≤ rectangles.length ≤ 100,0000 ≤ top ≤ bottom < grid.length and 0 ≤ left ≤ right < grid[0].lengthA rectangle can hold 10^6 blocks, and there can be 10^5 rectangles. Adding blocks one by one costs up to 10^11 additions.
A table built in 10^6 steps answers each rectangle with four reads. A total can reach 10^12, so use 64-bit integers.