84. 柱状图中最大的矩形 python

heights.append(0)是为了防止是5,6,7,8这种正序的,没办法取边界的情况
题目链接:
https://leetcode-cn.com/problems/largest-rectangle-in-histogram/

def largestRectangleArea(self, heights: List[int]) -> int:
        heights.append(0)
        stack = [-1]
        res = 0 
        for i in range(len(heights)):
            while heights[i]<heights[stack[-1]]:
                h = heights[stack.pop()]
                w = i-stack[-1]-1
                res= max(h*w,res)
            stack.append(i)
        while stack:
            stack.pop()
        return res
发布了16 篇原创文章 · 获赞 1 · 访问量 2834

猜你喜欢

转载自blog.csdn.net/weixin_43436824/article/details/105484644