Description
You are given a 0-indexed integer matrix grid and an integer k.
Return the number of submatrices that contain the top-left element of the grid, and have a sum less than or equal to k.
Example 1:
Input: grid = [[7,6,3],[6,6,1]], k = 18 Output: 4 Explanation: There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.
Example 2:
Input: grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20 Output: 6 Explanation: There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.
Constraints:
m == grid.lengthn == grid[i].length1 <= n, m <= 10000 <= grid[i][j] <= 10001 <= k <= 109
Solutions
The code uses a 2D prefix sum approach to count submatrices with a sum of at most k. For each cell in the grid, it computes the cumulative sum from (0,0) to that cell using the formula: current = grid[row][col] + top + left - diagonal, which adds values from above and to the left while subtracting the diagonal cell to avoid double-counting. After updating each cell's value to its prefix sum, it increments a counter if the sum is within the limit k.
Language: javascript(2026-03-18 09:51)DONE
CPU Performance59.46%
Memory Performance62.16%
/**
* @param {number[][]} grid
* @param {number} k
* @return {number}
*/
var countSubmatrices = function(grid, k) {
const m = grid.length;
const n = grid[0].length;
let res = 0;
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
const top = row > 0 ? grid[row - 1][col] : 0;
const left = col > 0 ? grid[row][col - 1] : 0;
const diag = row > 0 && col > 0 ? grid[row - 1][col - 1] : 0;
grid[row][col] += top + left - diag;
if (grid[row][col] <= k) {
res++;
}
}
}
return res;
};