Skip to content

Commit 85f7cfd

Browse files
Sync LeetCode submission Runtime - 11 ms (79.44%), Memory - 90.3 MB (96.67%)
1 parent e62888b commit 85f7cfd

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p>
2+
3+
<p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
<img alt="" src="https://assets.leetcode.com/uploads/2024/01/01/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
8+
<pre>
9+
<strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18
10+
<strong>Output:</strong> 4
11+
<strong>Explanation:</strong> 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.</pre>
12+
13+
<p><strong class="example">Example 2:</strong></p>
14+
<img alt="" src="https://assets.leetcode.com/uploads/2024/01/01/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
15+
<pre>
16+
<strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20
17+
<strong>Output:</strong> 6
18+
<strong>Explanation:</strong> 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.
19+
</pre>
20+
21+
<p>&nbsp;</p>
22+
<p><strong>Constraints:</strong></p>
23+
24+
<ul>
25+
<li><code>m == grid.length </code></li>
26+
<li><code>n == grid[i].length</code></li>
27+
<li><code>1 &lt;= n, m &lt;= 1000 </code></li>
28+
<li><code>0 &lt;= grid[i][j] &lt;= 1000</code></li>
29+
<li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li>
30+
</ul>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public:
3+
int countSubmatrices(vector<vector<int>>& grid, int k) {
4+
int n = grid.size();
5+
int m = grid[0].size();
6+
int ans = 0;
7+
for (int i=0; i<n; i++) {
8+
for (int j=0; j<m; j++) {
9+
if (i > 0) grid[i][j] += grid[i-1][j];
10+
if (j > 0) grid[i][j] += grid[i][j-1];
11+
if (i > 0 && j > 0) grid[i][j] -= grid[i-1][j-1];
12+
ans += grid[i][j] <= k;
13+
}
14+
}
15+
return ans;
16+
}
17+
};

0 commit comments

Comments
 (0)