leetcode-Largest Rectangle in Histogram

22 篇文章 0 订阅
2 篇文章 0 订阅

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.


题意:给出h数组为宽度为1的矩形柱的高度,求这堆矩形柱中最大的矩形面积。

分析:关键是找到以h[i]为最低的连续矩形的最左和最右位置left[i],right[i],即找到h[i]左边和右边第一个小于h[i]的位置

一般方法:遍历矩形的左右边界,复杂度O(n^2)

O(n)方法:遍历h,若栈为空或h[i]>=栈顶位置的高度,i入栈;否则,一直出栈直到满足h[i]>=栈顶位置的高度

出栈时计算面积,right为i-1,left为栈中的前一个元素(此时的栈顶)+1

遍历后,若栈不为空,依次出栈并计算面积,right为len-1,left同上

原理:由于h[i]>=栈顶位置的高度才压栈,所以出栈时的right一定为当前元素i,即右边第一个小于h[top]的位置

而由于压入i前先把>=h[i]的都出栈,那么栈内一定是高度严格递增的,left即为栈内前一个元素,即左边第一个小于h[top]的位置

注意:h[i]>=栈顶位置的高度入栈,考虑了重复元素的情况,只记录重复元素的最后出现位置


代码:

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        int len = height.size();
        stack<int> st;
        
        int ans = 0;
        for(int i=0; i<len; i++)
        {
            while(!st.empty() && height[st.top()]>=height[i])
            {
                int curi = st.top();
                st.pop();
                int now;
                if(st.empty()) now = height[curi]*i;
                else now = height[curi]*(i-st.top()-1);
                if(now>ans) ans = now;
            }
            st.push(i);
        }
        while(!st.empty())
        {
            int curi = st.top();
            st.pop();
            int now;
            if(st.empty()) now = height[curi]*len;
            else now = height[curi]*(len-st.top()-1);
            if(now>ans) ans = now;
        }
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值