85. Maximum Rectangle

https://leetcode.com/problems/maximal-rectangle/

solution

  • 单调栈: 按行迭代,每一行都视为柱状图的底部,对每一行求柱状图的最大面积

class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        if not matrix:
            return 0

        n = len(matrix[0])
        heights = [0] * (n + 1)
        max_area = 0

        for row in matrix:
            # 构建如84题的高度
            for i in range(n):
                heights[i] = heights[i] + 1 if row[i] == "1" else 0

            stack = [-1]
            for i in range(n + 1):
                # 单调栈: 右边第一个高度比自己小的index构成矩形
                while heights[i] < heights[stack[-1]]:
                    h = heights[stack.pop()]
                    w = i - stack[-1] - 1  # 左右两边第一个比自己小
                    max_area = max(max_area, h * w)
                stack.append(i)

        return max_area

时间复杂度:O(mn) 空间复杂度:O(n)

  • 动态规划: 一开始想到的dp没法处理前面一个单元是正方形,后面连着的只是单个

时间复杂度:O() 空间复杂度:O()

follow up

84 Largest Rectangle in Histogram

221 Maximal Square

Last updated