题目描述
解法:单调栈(Python)
详细参考 powcai的解
这里说一下在 h e i g h t s [ . . ] heights[..] heights[..]首尾添加0的作用,首处填0是便于计算最大面积取第一个柱子的情况;尾处填0是便于处理在遍历完之后栈不空的情况,对比LeetCode的官方题解可以知道,在最后栈不空时需要弹出所有元素计算最大面积,而尾处的0便起到了这个作用。
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
st = []
heights = [0] + heights + [0]
res = 0
for i in range(len(heights)):
while st and heights[st[-1]] > heights[i]:
tmp = st.pop()
res = max(res, (i - st[-1] - 1) * heights[tmp])
st.append(i)
return res