清单
● 84.柱状图中最大的矩形
LeetCode #84 柱状图中最大的矩形
1. 题目
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
2. 思路
- 双指针法:
- 通过左右指针遍历数组, 分别记录当前元素左右两端高度低于该柱子的角标
- 遍历数组, 计算当前遍历柱子所能勾勒出的最大矩形面积
- 单调栈:
- 最大矩形面积 —> 递减栈 —> 遍历元素,栈顶,栈底(最大面积的高度和宽度)
3. 代码实现
#双指针
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
length = len(heights)
min_left, min_right = [0] * length, [0] * length
result = 0
#左指针
min_left[0] = -1
for i in range(1, length):
temp = i - 1
while temp >= 0 and heights[temp] >= heights[i]:
temp = min_left[temp]
min_left[i] = temp
#右指针
min_right[length-1] = length
for i in range(length-2, -1, -1):
temp = i + 1
while temp < length and heights[temp] >= heights[i]:
temp = min_right[temp]
min_right[i] = temp
#遍历数组
for i in range(length):
area = heights[i] * (min_right[i] - min_left[i] - 1)
result = max(area, result)
return result
#单调栈
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.insert(0, 0)
heights.append(0)
stack = [0]
result = 0
for i in range(1, len(heights)):
if heights[i] > heights[stack[-1]]:
stack.append(i)
elif heights[i] == heights[stack[-1]]:
stack.pop()
stack.append(i)
else:
while stack and heights[i] < heights[stack[-1]]:
mid = stack[-1]
stack.pop()
if stack:
W = i - stack[-1] - 1
H = heights[mid]
result = max(H * W, result)
stack.append(i)
return result