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.


O(n2)复杂度肯定TLE,所以我都没有尝试(不知道这是不是个好习惯,或许尝试一下,能柳暗花明?)

不会做,我果然是个菜鸡

reference:参考来源

思路:用栈来保存之前的信息 O(n)

用栈来存储当前的height以及索引信息(大于等于目前height的最小的index),这样,如果新来一个h,如果它大于当前栈顶的高度值,则将它以及它对应的index入栈

如果它等于,则忽略(也可以进栈,但是无意义,因为索引值的信息是大于等于目前height的最小的index),所以其信息已经在栈中。

如果h<stack[top],则将所有大于等于h的元素出栈,并在出栈过程中,计算面积并更新面积的最大值。完了以后,将该h进栈,并且该h对应的索引值应该是大于等于h的height的最小index,即push(height[i],index) 而不是push(height[i],i)。

class Solution {
public:
    int hei[40000];
    int idx[40000];
    int top = -1;
    void push(int h,int i){
        top++;
        hei[top] = h;
        idx[top] = i;
    }
    int largestRectangleArea(vector<int> &height) {
        int r = 0;
       for(int i=0;i<height.size();i++){
           if(top==-1 || height[i]>hei[top]){
                push(height[i],i);
           }else{
               if(height[i]<hei[top]){
                   int mi=2147483647,index = -1;
                   while(top>-1 && height[i]<=hei[top]){
                       index = idx[top];
                       mi = min(mi,hei[top]);
                       r = max(r,mi*(i-index));
                       top--;
                   }
                    push(height[i],index);
               }
           }
       }
       while(top!=-1){
           int mi = hei[top];
           int index = idx[top];
           r = max(r,(int)(height.size()-index)*mi);
           top--;
       }
       return r;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值