forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximal-rectangle.py
51 lines (45 loc) · 1.37 KB
/
maximal-rectangle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Time: O(n^2)
# Space: O(n)
#
# Given a 2D binary matrix filled with 0's and 1's,
# find the largest rectangle containing all ones and return its area.
#
class Solution:
# @param matrix, a list of lists of 1 length string
# @return an integer
def maximalRectangle(self, matrix):
if not matrix:
return 0
result = 0
m = len(matrix)
n = len(matrix[0])
L = [0 for _ in xrange(n)]
H = [0 for _ in xrange(n)]
R = [n for _ in xrange(n)]
for i in xrange(m):
left = 0
for j in xrange(n):
if matrix[i][j] == '1':
L[j] = max(L[j], left)
H[j] += 1
else:
L[j] = 0
H[j] = 0
R[j] = n
left = j + 1
right = n
for j in reversed(xrange(n)):
if matrix[i][j] == '1':
R[j] = min(R[j], right)
result = max(result, H[j] * (R[j] - L[j]))
else:
right = j
return result
if __name__ == "__main__":
matrix = ["01101",
"11010",
"01110",
"11110",
"11111",
"00000"]
print Solution().maximalRectangle(matrix)