【力扣刷题】84. 柱状图中最大的矩形-单调栈
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
示例 1:
输入:heights = [2,1,5,6,2,3] 输出:10 解释:最大的矩形为图中红色区域,面积为 10
示例 2:
输入: heights = [2,4] 输出: 4
提示:
1 <= heights.length <=105
0 <= heights[i] <= 104
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int>st;
heights.insert(heights.begin(),0);
heights.push_back(0);
int n=heights.size(),ans=0;
st.push(0);
for(int i=1;i<n;i++){
int tem=heights[i];
if(tem>heights[st.top()]){
st.push(i);
}else if(tem==heights[st.top()]){
st.pop();
st.push(i);
}else{
while((!st.empty()&&tem<=heights[st.top()])){
int last=st.top();
st.pop();
if(!st.empty()){
int h=heights[last];
int w=i-st.top()-1;
cout<<"h="<<h<<endl;
cout<<"w="<<w<<endl;
ans=max(ans,h*w);
}
}
st.push(i);
}
}
return ans;
}
};
版权声明:
作者:Zhang, Hongxing
链接:http://zhx.info/archives/616
来源:张鸿兴的学习历程
文章版权归作者所有,未经允许请勿转载。
THE END
二维码
文章目录
关闭