接雨水
class Solution {
public:
int trap(vector<int>& height) {
stack<int> st;
int res=0;
for(int i=0;i<height.size();i++){
int prev=i;
int count=0;
while(!st.empty()&&height[st.top()]<height[i]){
int tmp=st.top();
st.pop();
if(!st.empty()){
int len=tmp-st.top();
count+=len;
res+=len*(height[i]-height[tmp]);
}
prev=tmp;
}
if(st.empty()){
res-=(height[i]-height[prev])*count;
}
st.push(i);
}
return res;
}
};
最大矩形面积
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res=0;
stack<int> st;
heights.push_back(-1);
for(int i=0;i<heights.size();i++){
while(!st.empty()&&heights[st.top()]>=heights[i]){
int tmp=st.top();
st.pop();
if(!st.empty()){
res=max(res,(i-1-st.top())*heights[tmp]);
}else{
res=max(res,i*heights[tmp]);
}
}
st.push(i);
}
return res;
}
};