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.

大致题意:给一个数组,数组的值为柱状图的高度,求其中最大的面积(宽度为1)

自己写的O(n^2) 就不献丑了,这里有一个O(n), 原文:https://www.geeksforgeeks.org/largest-rectangle-under-histogram/

 

思路:从头到尾遍历,求 以h(x)(0 <= x <=n) (第x个柱子的高度)为最小高度 的矩形的最大面积。(有点绕嘴- . -),那么需要知道前边第一个比h(x)小的柱子的坐标的下一个(前引索) 和 最后边第一个比h(x)小的柱子的坐标的上一个(后引索)。(说的有点乱)。。比如!!!

求以第5个柱子为最小高度的最大面积 , 那么我们可以看到,前引索为2(第三个柱子),后引索为5(第六个柱子),面积为(5-2+1)*2.

就这样,遍历一遍找出最大面积。

问题的关键就是找出前后引索,伪算法:

循环(i < l):

      新建一个栈(储存引索,而不是数组的值)

      if 如果栈空 或者 遍历到的柱子高度 >= 栈顶引索对应的柱子高度

                则入栈; i++; (这样入栈,造成一个单调递增栈)

      else 如果 遍历到的柱子高度 < 栈顶引索对应的柱子高度   ( 因为i对应的柱子比前一个矮,所以后引索为 i )    注意!!! 下边没有i++!!!!

               记录栈顶引索;(因为栈单调递增,所以前引索就是第一个)

                栈顶出栈;

                有前后引索,计算面积;

 

具体代码(C++):

#include<iostream> 
#include<stack> 
using namespace std; 

int getMaxArea(int hist[], int n) 
{ 
 
    stack<int> s; 
  
    int max_area = 0;  
    int tp;  
    int area_with_top;  
   
    int i = 0; 
    while (i < n) 
    { 
        if (s.empty() || hist[s.top()] <= hist[i]) 
            s.push(i++); 
  
        else
        { 
            tp = s.top();  
            s.pop(); 
            area_with_top = hist[tp] * (s.empty() ? i :  i - s.top() - 1); 
  
            if (max_area < area_with_top) 
                max_area = area_with_top; 
        } 
    } 
   
    while (s.empty() == false) //如果没有遍历完
    { 
        tp = s.top(); 
        s.pop(); 
        area_with_top = hist[tp] * (s.empty() ? i :  
                                i - s.top() - 1); 
  
        if (max_area < area_with_top) 
            max_area = area_with_top; 
    } 
  
    return max_area; 
} 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值