力扣的 柱状图中最大的矩形 解法 (Python3)
题目描述:
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
![以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。](https://img-blog.csdnimg.cn/20200330182912496.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NodXR1MjAxOA==,size_16,color_FFFFFF,t_70)
示例:
输入: [2,1,5,6,2,3]
输出: 10
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-rectangle-in-histogram
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
参考程序1:
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
lh = len(heights)
l, r, result = [-1] * lh, [lh] * lh, 0
for i in range(1, lh):
j = i - 1
while j >= 0 and heights[j] >= heights[i]:
j = l[j]
l[i] = j
for i in range(lh - 2, -1, -1):
j = i + 1
while j < lh and heights[j] >= heights[i]:
j = r[j]
r[i] = j
for i in range(lh):
result = max(result, heights[i] * (r[i] - l[i] - 1))
return result
运行结果1: