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.

思路:如果当前大或者相等,说明有可能是新的Rectangle的起点,入栈i++

        如果当前小,那么从栈顶弹出来,当做右边界进行计算面积,这时候不如栈.所有信息都在栈里面

 

另外一种思路是二分,很好写。

 int largestRectArea(vector<int> &h) {
        stack<int> p;
        int i = 0, m = 0;
        h.push_back(0);
        while(i < h.size()) {
            if(p.empty() || h[p.top()] <= h[i])
                p.push(i++);
            else {
                int t = p.top();
                p.pop();
                m = max(m, h[t] * (p.empty() ? i : i - p.top() - 1 ));
            }
        }
        return m;
    }

 

posted @ 2013-09-04 14:05  一只会思考的猪  阅读(153)  评论(0编辑  收藏  举报