84. Largest Rectangle in Histogram

Posted ruruozhenhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

Example:

Input: [2,1,5,6,2,3]
Output: 10

my code:(very inefficient)

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int len = heights.size();
        int res = 0;
        for (int i = 0; i < len; ++i) {
            int nums = 1;
            for (int j = i+1; j < len; ++j) {
                if (heights[j] >= heights[i])
                    nums++;
                else 
                    break;
            }
            for (int k = i-1; k >= 0; --k) {
                if (heights[k] >= heights[i])
                    nums++;
                else
                    break;
            }
            res = max(res, heights[i]*nums);
        }
        return res;
    }
};
Runtime: 1664 ms, faster than 1.28% of C++ online submissions for Largest Rectangle in Histogram.

 

height efficient code:

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int len = heights.size();
        int res = 0;
        stack<int> s;
        heights.push_back(0);
        for (int i = 0; i <= len; ++i) {
            int h = i==len ? 0 : heights[i];
            while (!s.empty() && h < heights[s.top()]) {
                int height = heights[s.top()];
                s.pop();
                int start = s.empty() ? -1 : s.top();
                int nums = i - start - 1;
                res = max(res, height*nums);
            }
            s.push(i);
        }
        
        return res;
    }
};

Runtime: 12 ms, faster than 45.96% of C++ online submissions for Largest Rectangle in Histogram.

stack中的数据(索引)升序进行排列,遇到小于前面的数开始计算,并将stack中比当前元素大的数pop。

 

以上是关于84. Largest Rectangle in Histogram的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 84. Largest Rectangle in Histogram

leetcode 84. Largest Rectangle in Histogram

84. Largest Rectangle in Histogram. 单调栈

84. Largest Rectangle in Histogram. 单调栈

leetcode 84. Largest Rectangle in Histogram

Leetcode 84: Largest Rectangle in Histogram