84. Largest Rectangle in Histogram(题目链接)
Hard
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.
Example:
Input: [2,1,5,6,2,3]
Output: 10
方法1:暴力+优化
如何优化?
只有在遇到局部的峰值的时候,才计算
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
smallest = 0
rlt = 0
for i in range(len(heights)):
if i + 1 < len(heights) and heights[i] <= heights[i + 1]:
continue
area = heights[i]
min_h = heights[i]
for j in range(i - 1, -1, -1):
min_h = min(min_h, heights[j])
area = max(area, (i - j + 1) * min_h )
rlt = max(rlt, area)
return rlt
方法2:使用栈
参考:https://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
if not heights:
return 0
rlt = 0
stack = []
heights.append(0)
i = 0
while i < len(heights):
if not stack or heights[i] >= heights[stack[-1]]:
stack.append(i)
i += 1
continue
top = stack.pop()
# 算间距的时候,不能用i-top, 测试 4,2,0,3,2,5,0
rlt = max(rlt, heights[top] * (i if not stack else i - stack[-1] - 1))
return rlt