84. 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 heights = [2,1,5,6,2,3],
return 10.


栈中存储的是上一个比当前高度小的条形的下标,用于计算下一个矩形的底长i-s.top()-1,若栈为空则底长为i。

注意考虑有连续重复高度的条形时,记录的永远是最后一个条形的下标,因为循环时已经将前面大于等于它的下标pop掉了。

整体思路参考博客:http://www.cnblogs.com/grandyang/p/4322653.html

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

猜你喜欢

转载自blog.csdn.net/jifeng7288/article/details/79939591
今日推荐