[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.

暴力解法,遍历左边界,超时。

class Solution {
public:
    int largestRectangleArea(vector<int>& height) {
        int area = 0;
        int minheight = 0;
        int res = 0;
        for(int i=0; i<height.size(); ++i){
            minheight =height[i];
            for(int j=i; j<height.size(); ++j){
                minheight = height[j]<minheight?height[j]:minheight;
                area = area > minheight*(j-i+1)?area:minheight*(j-i+1);
            }
            res = res>area?res:area;
        }
        return res;
    }
};

双栈做法,复杂度O(N).

Actually, we can decrease the complexity by using stack to keep track of the height and start indexes. Compare the current height with previous one.

Case 1: current > previous (top of height stack)
Push current height and index as candidate rectangle start position.

Case 2: current = previous
Ignore.

Case 3: current < previous
Need keep popping out previous heights, and compute the candidate rectangle with height and width (current index - previous index). Push the height and index to stacks.

(Note: it is better use another different example to walk through the steps, and you will understand it better).
[LeetCode]Largest Rectangle in Histogram_第1张图片


这个解法核心在于对数组进行不断的削减操作,把一些已经遍历过的解去除。

class Solution {
public:
    int largestRectangleArea(vector<int>& height) {
       stack<int> index;
       stack<int> h;
       if(height.size()==0)
            return 0;
       index.push(0);
       h.push(height[0]);
       int area = 0;
       for(int i=1; i<height.size(); ++i){
           if(h.empty()||height[i]>h.top()){
               index.push(i);
               h.push(height[i]);
           }
           else if(height[i]<h.top()){
               int tempIdx = 0;
               while(!h.empty() && height[i]<=h.top()){
                  tempIdx = index.top();
                  area = area>(i-index.top())*h.top()?area:(i-index.top())*h.top();
                  h.pop();
                  index.pop();
               }
               index.push(tempIdx);
               h.push(height[i]);
           }
       }
       while(!h.empty()){
           area = area >(height.size()-index.top())*h.top()? area:(height.size()-index.top())*h.top();
           h.pop();
           index.pop();
       }
       return area;
    }
};


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