python-leetcode-柱状图中最大的矩形
84. 柱状图中最大的矩形 - 力扣(LeetCode)
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
stack = [] # 维护一个单调递增栈
max_area = 0
heights.append(0) # 添加一个哨兵高度 0,确保所有柱子都能被处理
for i, h in enumerate(heights):
while stack and heights[stack[-1]] > h:
height = heights[stack.pop()]
width = i if not stack else i - stack[-1] - 1
max_area = max(max_area, height * width)
stack.append(i)
return max_area