-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathfind-sorted-submatrices-with-maximum-element-at-most-k.cpp
78 lines (74 loc) · 2.48 KB
/
find-sorted-submatrices-with-maximum-element-at-most-k.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Time: O(m * n)
// Space: O(m)
// mono stack
class Solution {
public:
long long countSubmatrices(vector<vector<int>>& grid, int k) {
const auto& count = [](const auto& heights) {
int result = 0;
vector<int> stk;
for (int i = 0, curr = 0; i < size(heights); ++i) {
while (!empty(stk) && heights[stk.back()] >= heights[i]) {
const int j = stk.back(); stk.pop_back();
curr -= (heights[j] - heights[i]) * (j - (!empty(stk) ? stk.back() : -1));
}
stk.emplace_back(i);
curr += heights[i];
result += curr;
}
return result;
};
int64_t result = 0;
vector<int> heights(size(grid));
for (int j = size(grid[0]) - 1; j >= 0; --j) {
for (int i = 0; i < size(grid); ++i) {
if (grid[i][j] > k) {
heights[i] = 0;
} else if (j + 1 < size(grid[0]) && grid[i][j] >= grid[i][j + 1]) {
++heights[i];
} else {
heights[i] = 1;
}
}
result += count(heights);
}
return result;
}
};
// Time: O(m * n)
// Space: O(m)
// mono stack, dp
class Solution2 {
public:
long long countSubmatrices(vector<vector<int>>& grid, int k) {
const auto& count = [](const auto& heights) {
vector<int> dp(size(heights));
vector<int> stk;
for (int i = 0; i < size(heights); ++i) {
while (!empty(stk) && heights[stk.back()] >= heights[i]) {
stk.pop_back();
}
dp[i] = !empty(stk)
? dp[stk.back()] + heights[i] * (i - stk.back())
: heights[i] * (i - (-1));
stk.emplace_back(i);
}
return accumulate(cbegin(dp), cend(dp), 0);
};
int64_t result = 0;
vector<int> heights(size(grid));
for (int j = size(grid[0]) - 1; j >= 0; --j) {
for (int i = 0; i < size(grid); ++i) {
if (grid[i][j] > k) {
heights[i] = 0;
} else if (j + 1 < size(grid[0]) && grid[i][j] >= grid[i][j + 1]) {
++heights[i];
} else {
heights[i] = 1;
}
}
result += count(heights);
}
return result;
}
};