-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path85. Maximal Rectangle
30 lines (23 loc) · 976 Bytes
/
85. Maximal Rectangle
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
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix or not matrix[0]:
return 0
max_area = 0
cols = len(matrix[0])
heights = [0] * cols
for row in matrix:
for i in range(cols):
heights[i] = heights[i] + 1 if row[i] == '1' else 0
max_area = max(max_area, self.largestRectangleArea(heights))
return max_area
def largestRectangleArea(self, heights: List[int]) -> int:
stack = []
max_area = 0
heights.append(0) # Append a zero to handle remaining bars in the stack
for i in range(len(heights)):
while stack and heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i if not stack else i - stack[-1] - 1
max_area = max(max_area, h * w)
stack.append(i)
return max_area