题目内容
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
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.
Example:
Input: [2,1,5,6,2,3]
Output: 10
题目思路
对于从左向右的每一个矩形,计算以每一个矩形为高度的大矩形的面积(向左右延伸生成大矩形),面积最大的大矩形面积就是所求解。那么可以运用动态规划的方法,对于每一个矩形,分别计算可以向左侧和右侧延伸多少,最后相加计算出以它为高度到最大矩形面积,选择最大到数值作为结果。
程序代码
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
if not heights:
return 0
lh=len(heights)
if lh==1:
return heights[0]
res=0
left,right=[0]*lh,[0]*lh
#left:
for i in range(1,lh):
if heights[i-1]<heights[i]:
left[i]=0
else:
j=i-1
while j>=0 and heights[j]>=heights[i]:
j=j-left[j]-1
left[i]=i-j-1
#right:
for i in range(lh-2,-1,-1):
if heights[i+1]<heights[i]:
right[i]=0
else:
j=i+1
while j<=lh-1 and heights[j]>=heights[i]:
j=j+right[j]+1
right[i]=j-i-1
print(left,right)
for i in range(lh):
res=max(res,heights[i]*(left[i]+right[i]+1))
return res