HardNo. 0085
Maximal Rectangle — LeetCode 85 Python Solution
- Pattern
- Stack
- Topics
- Stack, Array, Dynamic Programming, Matrix, Monotonic Stack
- Reading time
- 6 min
- Source
- leetcode.com
The problem
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example
- 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.
Python solution
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
heights = [0] * len(matrix[0])
ans = 0
for row in matrix:
for j, v in enumerate(row):
if v == "1":
heights[j] += 1
else:
heights[j] = 0
ans = max(ans, self.largestRectangleArea(heights))
return ans
def largestRectangleArea(self, heights: List[int]) -> int:
n = len(heights)
stk = []
left = [-1] * n
right = [n] * n
for i, h in enumerate(heights):
while stk and heights[stk[-1]] >= h:
stk.pop()
if stk:
left[i] = stk[-1]
stk.append(i)
stk = []
for i in range(n - 1, -1, -1):
h = heights[i]
while stk and heights[stk[-1]] >= h:
stk.pop()
if stk:
right[i] = stk[-1]
stk.append(i)
return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights))Complexity
- Time
- O(m × n)where m is the number of rows in matrix and n is the number of columns in matrix
- Space · auxiliary
- O(n·m)or optimized
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 85. Maximal Rectangle is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1504 | Count Submatrices With All Ones | Medium |
| 2617 | Minimum Number of Visited Cells in a Grid | Hard |
| 0907 | Sum of Subarray Minimums | Medium |
| 0975 | Odd Even Jump | Hard |
| 1130 | Minimum Cost Tree From Leaf Values | Medium |
| 1526 | Minimum Number of Increments on Subarrays to Form a Target Array | Hard |
Frequently asked questions
- How hard is LeetCode 85. Maximal Rectangle?
LeetCode 85. Maximal Rectangle is rated Hard on LeetCode.
- What topics does LeetCode 85. Maximal Rectangle cover?
LeetCode 85. Maximal Rectangle is tagged Stack, Array, Dynamic Programming, Matrix and Monotonic Stack on LeetCode.