class Solution {
public:
int trap(vector<int>& height) {
stack<int> st;
int reslut = 0;
for(int i = 0;i < height.size();i++) {
while(!st.empty() && height[i] > height[st.top()]) {
int mid = height[st.top()];
st.pop();
if(!st.empty()) {
int h = min(height[i], height[st.top()]) - mid;
int w = i - st.top() - 1;
reslut += h * w;
}
}
st.push(i);
}
return reslut;
}
};
题目2:84. 柱状图中最大的矩形 - 力扣(LeetCode)
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.insert(heights.begin(), 0);
heights.push_back(0);
stack<int> st;
int reslut = 0;
for(int i = 0;i < heights.size();i++) {
while(!st.empty() && heights[i] < heights[st.top()]) {
int mid = heights[st.top()];
st.pop();
if(!st.empty()) {
int w = i - st.top() - 1;
reslut = max(reslut, mid * w);
}
}
st.push(i);
}
return reslut;
}
};