Leetcode--Largest Rectangle in Histogram

来源:互联网 发布:淘宝上卖adidas高仿鞋 编辑:程序博客网 时间:2024/06/07 22:52

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.


Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].


The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.


思路:如果给定height数组是一个非递减的数组,如{1,2,3} 那么我们只需要遍历所有的数组元素,计算height[i]*(height.size()-i)的最大值

但实际中总会出现非递增的情况,如{1,3,4,2} 这时需要一个辅助空间--stack ,并保证stack中的元素都是非递减的。

如1入栈,3入栈,4入栈,当到最后一个元素时,2小于4, 它入栈后就无法保证stack的非递减性了。这时,将所有大于2的栈中元素出栈,4、3出栈,并用2替补所有出栈的元素。这样2就3次入栈。最后栈中的元素为:1,2,2,2  这就是个非递减的数组,可以按照上面提到的 “遍历所有的数组元素,计算height[i]*(height.size()-i)的最大值”得出最后的结果


class Solution {public:    #define MAX(a,b)  ((a)>=(b))?(a):(b)        int largestRectangleArea(vector<int> &height) {        if(height.size()<=0)            return 0;        else if(height.size()==1)            return height[0];        stack<int> stk;        int ma=0;        for(int i=0;i<height.size();i++)        {            if(stk.empty()||height[i]>=stk.top())                stk.push(height[i]);            else if(height[i]<stk.top())            {                int count=0;                while(!stk.empty()&&stk.top()>height[i])                {                    ++count;                    ma=MAX(ma,count*stk.top());                    stk.pop();                }                                for(int j=0;j<count+1;j++)                    stk.push(height[i]);            }        }                int count=0;        while(!stk.empty())        {            ++count;            ma=MAX(ma,count*stk.top());            stk.pop();        }                return ma;            }};




0 0