LeetCode: 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.

Solution:

    之前就知道这道题,也知道怎么写,但就是有些不太清楚,今天花时间想了想,总算想明白了。

两个队列,l和h,l代表当前的bar最左可以扩展到哪个位置。h代表响应bar的高度。

mitbbs上的大牛说,符合要求的面积最大的矩形,左边沿所在的bar,一定是在一个上升的曲线上,而右边沿所在的bar,一定是在一个下降的曲线上。为了让输入的数据符合要求,我们初始化的时候设置l[0] = h[0] = 0,表示数组中第一个值的左边的bar的高度是0。而cur_h = i==nSize? 0: height[i]; 在i == nSize的时候。将高度设置为0,就表示数组最有一个元素的右边的bar的高度是零。这样整个数组就符合我们的要求了。

假设队列中当前最大的高度是h,当遇到大于h的bar时,加入队列。

当遇到小于h的bar时,把队列中所有大于h的bar取出来,计算当前bar和队列中bar所能组成的矩形的面积。因为队列中h[top]的值肯定大于h[top-1]的值,所以当前bar和h[top-1]的bar组成的矩形一定在h[top]以内。

大概就是这样。先记下来,供以后看。

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int nSize = height.size();
        int l[nSize + 1];//left bar position
        int h[nSize + 1];//height of the left bar
        l[0] = h[0] = 0;
        int cur_h = 0;
        int max = 0;
        int top = 0;
        for(int i = 0 ; i<= nSize; ++i){
            cur_h = i==nSize? 0: height[i];
            int j = i;
            for(; h[top] > cur_h; j = l[top--]){
                int temp = (i - l[top]) * h[top];
                if(temp > max){
                    max = temp;
                }
            }
            if(cur_h > h[top]){
                h[++top] = cur_h;
                l[top] = j;
            }
        }
        return max;
    }
};


你可能感兴趣的:(LeetCode: Largest Rectangle in Histogram)