classSolution:defmaximalRectangle(self,matrix: List[List[str]]) ->int:ifnot matrix:return0 n =len(matrix[0]) heights = [0] * (n +1) max_area =0for row in matrix:# 构建如84题的高度for i inrange(n): heights[i]= heights[i]+1if row[i]=="1"else0 stack = [-1]for i inrange(n +1):# 单调栈: 右边第一个高度比自己小的index构成矩形while heights[i]< heights[stack[-1]]: h = heights[stack.pop()] w = i - stack[-1]-1# 左右两边第一个比自己小 max_area =max(max_area, h * w) stack.append(i)return max_area
时间复杂度:O(mn)
空间复杂度:O(n)
动态规划: 一开始想到的dp没法处理前面一个单元是正方形,后面连着的只是单个
classSolution:defmaximalRectangle(self,matrix: List[List[str]]) ->int: m, n =len(matrix),len(matrix[0]) ans =0 dp ={}for i inrange(m):for j inrange(n):if matrix[i][j] =='0': dp[(i,j)]= (0,0)else: x = dp[(i, j-1)][0]+1if j>0else1 y = dp[(i-1, j)][1]+1if i>0else1 dp[(i, j)]= (x, y) ans =max(x, y, ans) minWidth = x# vertical max possiblefor r inrange(i-1, i-y, -1): minWidth =min(minWidth, dp[(r, j)][0]) ans =max(ans, minWidth * (i-r+1))return ans