LeetCode-84-Largest Rectangle in Histogram

Posted 无名路人甲

tags:

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

解题思路:用栈辅助。维护一个升序的栈。当新元素小于栈顶元素,弹出该元素,并计算机最大面积。

    int largestRectangleArea(vector<int>& heights) {
        if(heights.size()==0) return 0;
        stack<int> stk;
        int maxArea = 0;
        int i=0;
        while(i < heights.size()){
            if(stk.empty() || heights[i] >= heights[stk.top()]){
                stk.push(i);
                i++;
            }else{
                int index = stk.top();
                stk.pop();
                maxArea = max(maxArea, heights[index]*(stk.empty()? i: i-stk.top()-1));
            }

        }
        while(!stk.empty()){
            int index = stk.top();
            stk.pop();
            maxArea = max(maxArea, heights[index]*(stk.empty()?i:i-stk.top()-1));
        }
        return maxArea;
        
    }

 



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

leetcode 84. Largest Rectangle in Histogram

Leetcode 84: Largest Rectangle in Histogram

LeetCode-84-Largest Rectangle in Histogram

leetcode 84 Largest Rectangle in Histogram ----- java

[LeetCode] 84. Largest Rectangle in Histogram Java

19.2.22 [LeetCode 84] Largest Rectangle in Histogram