文章目录
题意
思路
单调栈
代码
C++
class Solution {
public:
int trap(vector<int>& height) {
stack<int> s;
int ans = 0;
for (int i = 0; i < height.size(); i++) {
const int x = height[i];
while (!s.empty() && height[s.top()] <= x) {
const int h = height[s.top()];
s.pop();
if (s.empty())
break;
int left = s.top();
int dh = min(height[left], height[i]) - h;
ans += dh * (i - left - 1);
}
s.push(i);
}
return ans;
}
};