classSolution:deflargestRectangleArea(self, heights: List[int])->int:ifnot heights:return0
stack =[0]# 存下标
res =0for i inrange(1,len(heights)):# print(stack)ifnot stack or heights[i]>= heights[stack[-1]]:
stack.append(i)else:while stack and heights[stack[-1]]> heights[i]:
top = stack.pop()ifnot stack:# 栈空
res =max(res, i*heights[top])else:# stack[-1]和i 分别为小于heights[top]的最早出现的左右下标
res =max(res,(i-stack[-1]-1)*heights[top])
stack.append(i)while stack:
top = stack.pop()ifnot stack:# 栈空
res =max(res,len(heights)*heights[top])else:
res =max(res,(len(heights)-stack[-1]-1)*heights[top])return res
单调栈 + 哨兵 优化
开头 和 结尾 添加0元素,会少一些判断操作
类似的做法还有:链表中的头结点,冒泡排序
classSolution:deflargestRectangleArea(self, heights: List[int])->int:ifnot heights:return0
heights =[0]+ heights +[0]
stack =[0]# 存下标
res =0for i inrange(1,len(heights)):if heights[i]>= heights[stack[-1]]:
stack.append(i)else:while heights[stack[-1]]> heights[i]:
top = stack.pop()# stack[-1]和i 分别为小于heights[top]的最早出现的左右下标
res =max(res,(i-stack[-1]-1)*heights[top])
stack.append(i)# print(stack) # 最后栈stack剩的元素都是值为0的元素return res