Count Submatrices with Top-Left Element and Sum Less Than k⚓︎
Solution⚓︎
2D Prefix Sum: Define prefix[i+1][j+1]
to be the sum of elements of the submatrices with grid[0][0]
in the upper left corner and grid[i][j]
in the lower right corner. With this definition, there is no need to deal with the element sum of the first row/column.
See reference (Chinese).
- Time complexity: \(O(mn)\);
- Space complexity: \(O(mn)\).