-
Notifications
You must be signed in to change notification settings - Fork 3
/
42.cpp
51 lines (50 loc) · 1.5 KB
/
42.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
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
stack<int> st;
int res = 0;
for (int i = 0; i < height.size(); ++i) {
while (!st.empty() && height[i] >= height[st.top()]) {
int idx = st.top();
st.pop();
if (!st.empty()) {
int beforeIdx = st.top();
int h = min(height[beforeIdx], height[i]) - height[idx];
int w = i - beforeIdx - 1;
res += h * w;
}
}
st.push(i);
}
return res;
}
};
class Solution {
public:
int trap(vector<int>& height) {
int res = 0;
int left = 0;
int right = height.size() - 1;
int currentHeight = 0;
while (left < right) {
if (height[left] < height[right]) {
currentHeight = max(currentHeight, height[left]);
while (left + 1 < right && height[left + 1] <= currentHeight) {
left++;
res += currentHeight - height[left];
}
left++;
}
else {
currentHeight = max(currentHeight, height[right]);
while (right - 1 > left && height[right - 1] <= currentHeight) {
right--;
res += currentHeight - height[right];
}
right--;
}
}
return res;
}
};