Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
For example, given the following matrix:
1 | 1 0 1 0 0 |
Return 6.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
n = len(matrix[0])#列
height = [0]*(n+1)
ans = 0
for row in matrix:
for i in range(n):
if row[i] == '0':
height[i] = 0
else:
height[i] += 1
stack = [-1]
for i in range(n+1):
while height[i] < height[stack[-1]]:
h = height[stack.pop()]
w = i - stack[-1] - 1
ans = max(ans,w*h)
stack.append(i)
return ans