LeetCode——largest-rectangle-in-histogram1

Question

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 =10unit.

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

Code

/*
用堆栈计算每一块板能延伸到的左右边界
对每一块板
 堆栈顶更矮,这一块左边界确定,入栈
 堆栈顶更高,堆栈顶右边界确定,出栈,计算面积
 入栈时左边界确定
 出栈时右边界确定
 堆栈里元素是递增的
本质:中间的短板没有用!
复杂度 O(n)
*/

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        stack<int> tb;
        int res = 0;
        for (int i = 0; i < height.size(); i++) {
           while (!tb.empty() && height[tb.top()] >= height[i]) {
               int index = tb.top();
               tb.pop();
               if (tb.empty()) 
                   // 当前长度的最矮高度
                   res = max(i * height[index], res);
               else {
                  // 底 * 高
                   res = max((i - tb.top() - 1) * height[index], res);
               }
           }
           tb.push(i);
        }
        // 这里的n相当于相面的i遍历到height.size(); 
        // 所以用n来计算底的长度
        int n = height.size();
        while (!tb.empty()) {
            int index = tb.top();
            tb.pop();
            if (tb.empty())
                // 最矮的列
                res = max(n * height[index], res);
            else {
                res = max((n - tb.top() - 1) * height[index], res);
            }
        }
        
        return res;
    }
};
posted @ 2017-10-31 10:57  清水汪汪  阅读(126)  评论(0编辑  收藏  举报