Skip to content

3070. Count Submatrices with Top-Left Element and Sum Less Than k 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int countSubmatrices(vector<vector<int>>& grid, int k) {
    const int m = grid.size();
    const int n = grid[0].size();
    int ans = 0;
    vector<vector<int>> prefix(m + 1, vector<int>(n + 1));

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        prefix[i + 1][j + 1] =
            grid[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j];
        if (prefix[i + 1][j + 1] <= k)
          ++ans;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int countSubmatrices(int[][] grid, int k) {
    final int m = grid.length;
    final int n = grid[0].length;
    int ans = 0;
    int[][] prefix = new int[m + 1][n + 1];

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        prefix[i + 1][j + 1] = grid[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j];
        if (prefix[i + 1][j + 1] <= k)
          ++ans;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def countSubmatrices(self, grid: list[list[int]], k: int) -> int:
    m = len(grid)
    n = len(grid[0])
    ans = 0
    # prefix[i][j] := the sum of matrix[0..i)[0..j)
    prefix = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(m):
      for j in range(n):
        prefix[i + 1][j + 1] = (grid[i][j] + prefix[i][j + 1] +
                                prefix[i + 1][j] - prefix[i][j])
        if prefix[i + 1][j + 1] <= k:
          ans += 1

    return ans