Leetcode| 84. 柱状图中最大的矩形 Day60

84. Largest Rectangle in Histogram

单调栈内递增
  x
xx…x

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        heights.insert(0, 0)
        heights.append(0)
        stack = [0]
        res = 0

        for i in range(1, len(heights)):
            if heights[i] > heights[stack[-1]]:
                stack.append(i)
            elif heights[i] == heights[stack[-1]]:
                stack.pop()
                stack.append(i)
            else:
                while stack and heights[i] < heights[stack[-1]]:
                    mid = stack.pop()
                    h = heights[mid]
                    w = i - stack[-1] - 1
                    res = max(res, h * w)
                stack.append(i)

        return res

你可能感兴趣的:(算法,leetcode,算法,职场和发展)