forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
maximal-rectangle.py
77 lines (66 loc) · 2.1 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# Time: O(n^2)
# Space: O(n)
class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
def largestRectangleArea(heights):
increasing, area, i = [], 0, 0
while i <= len(heights):
if not increasing or (i < len(heights) and heights[i] > heights[increasing[-1]]):
increasing.append(i)
i += 1
else:
last = increasing.pop()
if not increasing:
area = max(area, heights[last] * i)
else:
area = max(area, heights[last] * (i - increasing[-1] - 1 ))
return area
if not matrix:
return 0
result = 0
heights = [0] * len(matrix[0])
for i in xrange(len(matrix)):
for j in xrange(len(matrix[0])):
heights[j] = heights[j] + 1 if matrix[i][j] == '1' else 0
result = max(result, largestRectangleArea(heights))
return result
# Time: O(n^2)
# Space: O(n)
# DP solution.
class Solution2(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
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