File tree 1 file changed +40
-1
lines changed
1 file changed +40
-1
lines changed Original file line number Diff line number Diff line change 1
1
// Time: O(m * n)
2
2
// Space: O(m)
3
3
4
- // mono stack, dp
4
+ // mono stack
5
5
class Solution {
6
+ public:
7
+ long long countSubmatrices (vector<vector<int >>& grid, int k) {
8
+ const auto & count = [](const auto & heights) {
9
+ int result = 0 ;
10
+ vector<int > stk;
11
+ for (int i = 0 , curr = 0 ; i < size (heights); ++i) {
12
+ while (!empty (stk) && heights[stk.back ()] >= heights[i]) {
13
+ const int j = stk.back (); stk.pop_back ();
14
+ curr -= (heights[j] - heights[i]) * (j - (!empty (stk) ? stk.back () : -1 ));
15
+ }
16
+ stk.emplace_back (i);
17
+ curr += heights[i];
18
+ result += curr;
19
+ }
20
+ return result;
21
+ };
22
+
23
+ int64_t result = 0 ;
24
+ vector<int > heights (size (grid));
25
+ for (int j = size (grid[0 ]) - 1 ; j >= 0 ; --j) {
26
+ for (int i = 0 ; i < size (grid); ++i) {
27
+ if (grid[i][j] > k) {
28
+ heights[i] = 0 ;
29
+ } else if (j + 1 < size (grid[0 ]) && grid[i][j] >= grid[i][j + 1 ]) {
30
+ ++heights[i];
31
+ } else {
32
+ heights[i] = 1 ;
33
+ }
34
+ }
35
+ result += count (heights);
36
+ }
37
+ return result;
38
+ }
39
+ };
40
+
41
+ // Time: O(m * n)
42
+ // Space: O(m)
43
+ // mono stack, dp
44
+ class Solution2 {
6
45
public:
7
46
long long countSubmatrices (vector<vector<int >>& grid, int k) {
8
47
const auto & count = [](const auto & heights) {
You can’t perform that action at this time.
0 commit comments