代码随想录算法训练营day60|| 第九章 单调栈

84.柱状图中最大的矩形

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。求在该柱状图中,能够勾勒出来的矩形的最大面积。

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int result=0;
        stack<int> st;
        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[st.top()]>heights[i]){
                    int mid=st.top();
                    st.pop();
                    if(!st.empty()){
                        int left=st.top();
                        int right=i;
                        int w=right-left-1;
                        int h=heights[mid];
                        result=max(result,w*h);
                    }
                }
                st.push(i);
            }
        }
        return result;
    }
};

版权声明:本文为wsq06209023原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。