Largest Rectangle in Histogram

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.

思路1:O(n^2),两层循环计算所有可能的矩阵面积。小数可以通过,大数级超时。

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        int n=height.size();
        if(n==0)
            return 0;
        int maxArea;
        for(int i=0;i<n;i++)
        {
            int width=height[i];
            for(int k=i;k<n;k++)
            {
                if(width*(n-i)<=maxArea)
                    break;
                width=min(width,height[k]);
                maxArea=max(maxArea,width*(k-i+1));
            }
        }
        return maxArea;
    }
};

 

思路2:使用一种单调递增的stack,可以用O(n)解决这道题目;主要是循环遍历,栈顶元素指向的heigh值如果小于height[i],则入栈i+1;如果大于height[i],则做这样的处理——将栈顶元素取出,这是有两种情况1)栈为空,则此时的area为目前的height值乘以i;2)栈不为空,计算此时的area。从而比较得到最大maxArea;

注意:一定要在height后面添加一元素0或者其他较小值,保证当可以对最后一个元素进行操作。

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

 

posted @ 2014-06-01 13:30  Awy  阅读(175)  评论(0编辑  收藏  举报