题意: 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