84. 柱状图中最大的矩形

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

求在该柱状图中,能够勾勒出来的矩形的最大面积。

 

以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。

 

图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。

示例:

输入: [2,1,5,6,2,3]
输出: 10

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-rectangle-in-histogram
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解:

这题我最开始写的和85一种解法,结果最后一个测试用例超时。。

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        if(heights.size()==0)
            return 0;
        int max_area=0;
        for(int i=0;i<heights.size();i++)
        {
            int min_height=INT_MAX;
            for(int ass_weight=1;ass_weight<=i+1;ass_weight++)
            {
                    min_hight=min(min_hight,heights[i-ass_weight+1]);
                    max_area=max(max_area,min_hight*ass_weight);
                
            }
        }
        return max_area;
    }
};

 别人提供的答案,用栈的方式,其实可以把这个想象成锯木板,如果木板都是递增的那我很开心,如果突然遇到一块木板i矮了一截,那我就先找之前最戳出来的一块(其实就是第i-1块),计算一下这个木板单独的面积,然后把它锯成次高的,这是因为我之后的计算都再也用不着这块木板本身的高度了。再然后如果发觉次高的仍然比现在这个i木板高,那我继续单独计算这个次高木板的面积(应该是第i-1和i-2块),再把它俩锯短。直到发觉不需要锯就比第i块矮了,那我继续开开心心往右找更高的。当然为了避免到了最后一直都是递增的,所以可以在最后加一块高度为0的木板。

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int> sta_int;
        //这块用来提供基础下标
        sta_int.push(-1);
        int index=0;
        int MaxArea=0;
        while(index<heights.size())
        {
            //比栈顶元素小,则弹出计算
            while(sta_int.top()!=-1&&heights[index]<=heights[sta_int.top()])
            {
                int tmp=sta_int.top();
                sta_int.pop();
                MaxArea=max(MaxArea,heights[tmp]*(index-sta_int.top()-1));
                //sta_int.pop();
            }
            sta_int.push(index);
            index++;
        }
        int length=heights.size();
        while(sta_int.top()!=-1)
        {
                int tmp=sta_int.top();
                sta_int.pop();
                MaxArea=max(MaxArea,(heights[tmp])*(length-sta_int.top()-1));
  
        }
        return MaxArea;
    }
};
原文地址:https://www.cnblogs.com/wangshaowei/p/12285236.html