> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Maximal Rectangle Python Solution with Tests

> Tested Python solution for LeetCode 85 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 85, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Dynamic Programming](/catalog/topics/dynamic-programming), [Stack](/catalog/topics/stack), [Matrix](/catalog/topics/matrix), [Monotonic Stack](/catalog/topics/monotonic-stack). [View on LeetCode](https://leetcode.com/problems/maximal-rectangle/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 85   # by problem number
lcpy gen -s maximal_rectangle   # by problem name
```

## Problem

Given a \<code>rows x cols\</code> binary \<code>matrix\</code> filled with \<code>0\</code>'s and \<code>1\</code>'s, find the largest rectangle containing only \<code>1\</code>'s and return \<em>its area\</em>.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2020/09/14/maximal.jpg)

```
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
```

```
Input: matrix = [["0"]]
Output: 0
```

```
Input: matrix = [["1"]]
Output: 1
```

### Constraints

* rows == matrix.length
* cols == matrix\[i].length
* 1 \<= rows, cols \<= 200
* matrix\[i]\[j] is '0' or '1'.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximal_rectangle/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximal_rectangle/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(rows * cols)
    # Space: O(cols)
    def maximal_rectangle(self, matrix: list[list[str]]) -> int:
        if not matrix or not matrix[0]:
            return 0

        cols = len(matrix[0])
        heights = [0] * cols
        best = 0
        for row in matrix:
            for j, val in enumerate(row):
                heights[j] = heights[j] + 1 if val == "1" else 0
            best = max(best, self.largest_rectangle_area(heights))
        return best

    def largest_rectangle_area(self, heights: list[int]) -> int:
        stack: list[int] = []
        best = 0
        extended = [*heights, 0]
        for i, h in enumerate(extended):
            while stack and extended[stack[-1]] >= h:
                height = extended[stack.pop()]
                left = stack[-1] if stack else -1
                best = max(best, height * (i - left - 1))
            stack.append(i)
        return best
```

## Complexity

| Time | Space |
| - | - |
| O(rows \* cols) | O(cols) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.