完结!撒花!
LeetCode 84.柱状图中最大的矩形
题目链接:
代码:
cpp
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.insert(heights.begin(),0);
heights.push_back(0);
int size = heights.size();
stack<int>st;
int result = 0;
st.push(0);
for(int i=1;i<size;i++){
if(heights[i]>=heights[st.top()]) st.push(i);
else{
while(!st.empty() && heights[i]<heights[st.top()]){
int mid = st.top();
st.pop();
if(!st.empty()){
int right = i;
int left = st.top();
int w = right - left - 1;
result = max(result, w*heights[mid]);
}
}
st.push(i);
}
}
return result;
}
};