84.柱状图中最大的矩形
思路: 与接雨水相似,本题栈需要递减栈,找到当前元素左右小于它的元素,然后求面积。数据首尾都要加0防止无法得到特殊情况的值。
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> st;
int result = 0;
heights.insert(heights.begin(),0);
heights.push_back(0);
st.push(0);
for(int i =1;i<heights.size();i++){
if(heights[i] > heights[st.top()]){
st.push(i);
}else if(heights[i] == heights[st.top()]){
st.pop();
st.push(i);
}else{
while(!st.empty()&&heights[i] < heights[st.top()]){
int mid = heights[st.top()];
st.pop();
if(!st.empty()){
int left = st.top();
int right = i;
int w = right - left -1;
int h = mid;
result = max(result,w*h);
}
}
st.push(i);
}
}
return result;
}
};