代码随想录算法训练营Day 60| 单调栈part03| 84.柱状图中最大的矩形
84.柱状图中最大的矩形
题目链接
一、双指针 向左向右找第一个矮一级的柱子下标
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
size = len(heights)
min_left_index = [0] * size
min_right_index = [0] * size
result = 0
min_left_index[0] = -1
for i in range(1, size):
temp = i - 1
while temp >= 0 and heights[temp] >= heights[i]:
temp = min_left_index[temp]
min_left_index[i] = temp
min_right_index[size-1] = size
for i in range(size-2, -1, -1):
temp = i + 1
while temp < size and heights[temp] >= heights[i]:
temp = min_right_index[temp]
min_right_index[i] = temp
for i in range(size):
area = heights[i] * (min_right_index[i] - min_left_index[i] - 1)
result = max(area, result)
return result
二、单调栈
'''
heights.insert(0, 0)
heights.append(0)
stack = [0]
res=0
for i in range(1,len(heights)):
while stack and heights[i]<heights[stack[-1]]:
mid = stack.pop()
if stack:
width = i - stack[-1] - 1
res = max(res, width * heights[mid])
stack.append(i)
return res