class Solution(object):
def maximalRectangle(self, mat):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if len(mat) == 0 or len(mat[0]) == 0:
return 0
H = len(mat)
W = len(mat[0])
largest = 0
heights = [0]*(W+1)
for j in range(H):
for i in range(W):
if mat[j][i] == '1':
heights[i] += 1
else:
heights[i] = 0
stack = []
for i in range(W+1):
while len(stack) != 0 and heights[stack[-1]] > heights[i]:
temp = stack[-1]
del stack[-1]
leftWidth = temp if len(stack) == 0 else temp-stack[-1]-1
rightWidth = i-temp-1
largest = max(largest, (leftWidth + rightWidth + 1) * heights[temp])
stack.append(i)
return largest
https://leetcode.com/problems/maximal-rectangle/#/description
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 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.