Implement a class NumMatrix. It is built once from a rectangular grid of integers and then answers many rectangle-sum queries.
NumMatrix(matrix):matrixis a list of rows, at least 1×1. Values may be negative. The grid never changes after construction.sum_region(r1, c1, r2, c2): return the sum of everymatrix[r][c]withr1 <= r <= r2andc1 <= c <= c2. Indexes are 0-based and inclusive, and always satisfyr1 <= r2,c1 <= c2and lie inside the grid.
m = NumMatrix([[2, 0, -1],
[4, 3, 5],
[1, 1, 1]])
m.sum_region(0, 0, 1, 1) # 9 (2 + 0 + 4 + 3)
m.sum_region(1, 1, 2, 2) # 10 (3 + 5 + 1 + 1)
m.sum_region(0, 2, 2, 2) # 5 (-1 + 5 + 1)
Constraints: up to 200×200 cells, up to 2·10^5 queries.
Every query must be O(1) after an O(rows × cols) setup. Summing the rectangle cell by cell, or row by row, fails the large test.
Show hint
precompute, for every (r, c), the sum of the top-left block ending there. Any rectangle is then a combination of four such blocks.