classSolution: deflargestRectangleArea(self, heights: List[int]) -> int: res = 0 st = [] heights.append(0) i = 0 while i < len(heights): ifnotlen(st) or heights[st[-1]] < heights[i]: st.append(i) else: cur = st.pop() width = i ifnotlen(st) else (i - st[-1] - 1) res = max(res, heights[cur] * width) i -= 1 i += 1 return res
defmaximalRectangle(self, matrix: List[List[str]]) -> int: matrix = [[int(x) for x in row] for row in matrix] sub_matrix = [] for row in matrix: sub_matrix.append(self.largestRectangleArea(row)) res = self.largestRectangleArea(sub_matrix) return res
classSolution: deflargestRectangleArea(self, heights: List[int]) -> int: res = 0 st = [] heights.append(0) i = 0 while i < len(heights): ifnotlen(st) or heights[st[-1]] < heights[i]: st.append(i) else: cur = st.pop() width = i ifnotlen(st) else (i - st[-1] - 1) res = max(res, heights[cur] * width) i -= 1 i += 1 return res
defmaximalRectangle(self, matrix): ifnotlen(matrix) ornotlen(matrix[0]): return0 res = 0 heights = [0for _ inrange(len(matrix[0]))] for i inrange(len(matrix)): for j inrange(len(matrix[i])): heights[j] = 0if matrix[i][j] == "0"else (1 + heights[j]) # 注意这里, res = max(res, self.largestRectangleArea(heights)) return res
left = [0] * n # initialize left as the leftmost boundary possible right = [n] * n # initialize right as the rightmost boundary possible height = [0] * n
maxarea = 0
for i inrange(m):
cur_left, cur_right = 0, n # update height for j inrange(n): if matrix[i][j] == '1': height[j] += 1 else: height[j] = 0 # update left for j inrange(n): if matrix[i][j] == '1': left[j] = max(left[j], cur_left) else: left[j] = 0 cur_left = j + 1 # update right for j inrange(n-1, -1, -1): if matrix[i][j] == '1': right[j] = min(right[j], cur_right) else: right[j] = n cur_right = j # update the area for j inrange(n): maxarea = max(maxarea, height[j] * (right[j] - left[j]))