Skip to content

Commit 8a94bd5

Browse files
authored
Update find-sorted-submatrices-with-maximum-element-at-most-k.cpp
1 parent 0b26e95 commit 8a94bd5

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

C++/find-sorted-submatrices-with-maximum-element-at-most-k.cpp

+40-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,47 @@
11
// Time: O(m * n)
22
// Space: O(m)
33

4-
// mono stack, dp
4+
// mono stack
55
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 {
645
public:
746
long long countSubmatrices(vector<vector<int>>& grid, int k) {
847
const auto& count = [](const auto& heights) {

0 commit comments

Comments
 (0)