-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy path85.maximal-rectangle.py
More file actions
110 lines (95 loc) · 2.7 KB
/
85.maximal-rectangle.py
File metadata and controls
110 lines (95 loc) · 2.7 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# Tag: Array, Dynamic Programming, Stack, Matrix, Monotonic Stack
# Time: O(NM)
# Space: O(M)
# Ref: -
# Note: -
# 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 1:
#
#
# 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.
#
# Example 2:
#
# Input: matrix = [["0"]]
# Output: 0
#
# Example 3:
#
# Input: matrix = [["1"]]
# Output: 1
#
#
# Constraints:
#
# rows == matrix.length
# cols == matrix[i].length
# 1 <= row, cols <= 200
# matrix[i][j] is '0' or '1'.
#
#
# Based On 84
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
n = len(matrix)
m = len(matrix[0])
dp = [0 for i in range(m + 1)]
res = 0
for i in range(n):
for j in range(m):
if matrix[i][j] == '1':
dp[j] += 1
else:
dp[j] = 0
res = max(res, self.cal(dp))
return res
def cal(self, dp: list) -> int:
res = 0
stack = []
for i in range(len(dp)):
while len(stack) > 0 and dp[i] < dp[stack[-1]]:
height = dp[stack[-1]]
stack.pop()
left = 0 if len(stack) == 0 else stack[-1] + 1
res = max(res, (i - left) * height)
stack.append(i)
return res
# 3 dp
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
m = len(matrix)
n = len(matrix[0])
left = [0] * n
right = [n] * n
height = [0] * n
res = 0
for i in range(m):
cur_left = 0
cur_right = n
# height dp
for j in range(n):
if matrix[i][j] == '1':
height[j] += 1
else:
height[j] = 0
# left dp
for j in range(n):
if matrix[i][j] == '1':
left[j] = max(left[j], cur_left)
else:
left[j] = 0
cur_left = j + 1
# right dp
for j in range(n - 1, -1, -1):
if matrix[i][j] == '1':
right[j] = min(right[j], cur_right)
else:
right[j] = n
cur_right = j
# area
for j in range(n):
res = max(res, (right[j] - left[j]) * height[j])
return res