Leetcode: 84. Largest Rectangle in Histogram

Description

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.

Example

Given heights = [2,1,5,6,2,3],
return 10.

思路

  • 假如已知数组为升序排列[1,2,3,5,8]

  • 则结果为(1 * 5) vs (2 * 4) vs (3 * 3) vs (5 * 2) vs (8 * 1),即通过升序方式来计算所有的面积,然后取最大值

  • 使用一个栈,来维护一个升序队列,如当前比栈顶大,直接入栈;比栈顶小,弹出并计算相应面积。注意判断栈为空的时候,即当前元素全部弹出去后,为空,此时应该怎么办。

  • 还有一种解释,即使用栈维护一个升序队列,如果当前小于栈顶,将栈顶弹出计算后,将栈顶替换为当前元素。画个图吧,容易理解。哈哈。

代码

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int len = heights.size();
        if(len == 0) return 0;
        
        stack<int> Stk;
        int res = -1, i = 0, index = 0, min_flag = INT_MAX;
        while(i < len){
           while(!Stk.empty() && heights[Stk.top()] > heights[i]){
               int h = heights[Stk.top()];
               Stk.pop();
               
               index = Stk.empty() ? i : i - Stk.top() - 1;
               res = max(res, h * index);
           }
           Stk.push(i);
           i++;
        }
        
    
        while(!Stk.empty()){
            int h = heights[Stk.top()];
            Stk.pop();
            index = Stk.empty() ? len : len - Stk.top() - 1;          
            res = max(res, h * index);
        }
    
        return res;
    }
};
posted @ 2017-06-13 22:04  JeffNice  阅读(212)  评论(0)    收藏  举报