Skip to content

Commit add2f7c

Browse files
committed
Maximal Rectangle
1 parent 17f133f commit add2f7c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

085 Maximal Rectangle.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
3+
'''
4+
5+
class Solution(object):
6+
def maximalRectangle(self, matrix):
7+
"""
8+
:type matrix: List[List[str]]
9+
:rtype: int
10+
"""
11+
if not matrix or not matrix[0]:
12+
return 0
13+
n = len(matrix[0])
14+
heights = [0 for __ in range(n + 1)]
15+
result = 0
16+
for row in matrix:
17+
for i in range(n):
18+
heights[i] = heights[i] + 1 if row[i] == '1' else 0
19+
stack = [-1]
20+
for i in range(n + 1):
21+
while heights[i] < heights[stack[-1]]:
22+
h = heights[stack.pop()]
23+
w = i - stack[-1] - 1
24+
result = max(result, h * w)
25+
stack.append(i)
26+
return result
27+
28+
29+
if __name__ == "__main__":
30+
assert Solution().maximalRectangle([['2', '1', '0', '1', '0', '1'],
31+
['0', '1', '0', '0', '1', '1'],
32+
['1', '1', '1', '1', '0', '1'],
33+
['1', '1', '1', '1', '0', '1']]) == 8

0 commit comments

Comments
 (0)