# 85. Maximum Rectangle

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

## solution

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

```python
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没法处理前面一个单元是正方形，后面连着的只是单个

```python
class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        m, n = len(matrix), len(matrix[0])
        ans = 0
        dp = {}

        for i in range(m):
            for j in range(n):
                if matrix[i][j] == '0':
                    dp[(i,j)] = (0,0)
                else:
                    x = dp[(i, j-1)][0]+1 if j>0 else 1
                    y = dp[(i-1, j)][1]+1 if i>0 else 1
                    dp[(i, j)] = (x, y)
                    ans = max(x, y, ans)
                    minWidth = x
                    # vertical max possible
                    for r in range(i-1, i-y, -1):
                        minWidth = min(minWidth, dp[(r, j)][0])
                        ans = max(ans, minWidth * (i-r+1))
        return ans
```

时间复杂度：O()\
空间复杂度：O()

## follow up

[84 Largest Rectangle in Histogram](/mle-interview/01_leetcode/dan-diao-zhan/84.-largest-rectangle-in-histogram.md)

[221 Maximal Square](/mle-interview/01_leetcode/09_dynamic_program/221.-maximal-square.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://longxingtan.gitbook.io/mle-interview/01_leetcode/dan-diao-zhan/85.-maximum-rectangle.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
