给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]
。
图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10
个单位。
示例:
输入: [2,1,5,6,2,3]
输出: 10
思路:
利用递增栈找到矩形的左右边界。
详细解释可以看这篇文章,写的很好:https://blog.csdn.net/Zolewit/article/details/88863970
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
res = 0
stack = list()
heights = [0] + heights + [0]
for i in range(len(heights)):
while stack and heights[stack[-1]] > heights[i]:
top = stack.pop()
res = max(res, (i - stack[-1] - 1) * heights[top])
stack.append(i)
return res