https://leetcode-cn.com/problems/trapping-rain-water/
單調棧應用,詳細講解 點我
class Solution {
public:
int trap(vector<int>& height) {
int sum = 0,cur = 0,n = height.size();
stack<int> s;
while(cur < n){
while(!s.empty() && height[cur] > height[s.top()]){
int t = s.top();
s.pop();
if(s.empty()) break;
sum += (cur - s.top() - 1) * (min(height[s.top()],height[cur]) - height[t]);
}
s.push(cur++);
}
return sum;
}
};