84.柱状图中最大的矩形

法一:每次遇到一个峰值往回进行处理

class Solution {
public:
	int largestRectangleArea(vector<int>& heights) {
        int res=0;
        for(int i=0;i<heights.size();i++)
        {
            if(i+1<heights.size()&&heights[i]<=heights[i+1])
                continue;
            int minx=heights[i];
            for(int j=i;j>=0;j--)
            {
                minx=min(minx,heights[j]);
                int are=(i-j+1)*minx;
                res=max(are,res);
            }
        }
    return res;
        }
};

法二:
利用栈,维持一个递增序列,当数组元素小于栈顶元素时进行弹栈处理,计算面积,递增序列的好处就是容易确定最小值和最大面积,方法很巧妙很难想到
在数组末尾添加一个0以便最后一个数据也能够进行处理

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        int res=0;
        stack<int>st;
        height.push_back(0);
        for(int i=0;i<height.size();i++)
        {
            if(st.empty()||height[st.top()]<height[i])
                st.push(i);
            else
            {
                int tmp=st.top();
                st.pop();
                int are=height[tmp]*(st.empty()?i:(i-st.top()-1));
                res=max(res,are);
                --i;
            }
        }
    return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41413511/article/details/88681507