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.

For example,
Given heights = [2,1,5,6,2,3],
return 10. 

思路:这题最早在CCF的考试上做过,第一反应都是用双层循环的办法,但是这里要学的是使用堆栈的思路来解,肯定就是用栈来减少循环的次数,所以需要把这道题重新思考一下。如果一层循环的话,如何解?
就是每个柱体遍历一次,换句话说就是以该柱体为最高所能占据的最大面积是多大,比如对第一个柱体2,他能占的最大面积就是2*1;而对于第二个柱体1,他能占的最大面积是1* 5。这样就能一次遍历得出结果。但是该柱体最大面积的柱体高已知,那柱体宽怎么求呢?仔细思考,有一个高度不断递增的连续柱体,对于之间的柱体来说,每个柱体的最大面积都是在增加的,这时候就不断压栈,知道遇到一个开始递减的柱体,因为这时候对于之前最高的哪个柱体来说,它的最大面积已经定了,所以把它弹出栈,计算以它为最高柱体的当前最大面积,以此类推,具体看代码就明白了。

参考代码:

def largestRectangleArea(self, height):
        increasing, area, i = [], 0, 0
        while i <= len(height):
            if not increasing or (i < len(height) and height[i] > height[increasing[-1]]):
                increasing.append(i)
                i += 1
            else:
                last = increasing.pop()
                if not increasing:
                    area = max(area, height[last] * i)
                else:
                    area = max(area, height[last] * (i - increasing[-1] - 1 ))
        return area
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值