classSolution{publicintmaximalRectangle(char[][] matrix){if(matrix ==null|| matrix.length ==0){return0;}// 看成【對每層,進行柱狀圖最大面積判斷】即可(相當于固定底)int max =0;int[] heights =newint[matrix[0].length];for(int i =0; i < matrix.length; i++){for(int j =0; j < matrix[0].length; j++){if(matrix[i][j]=='1'){heights[j]++;}else{heights[j]=0;}}max =Math.max(max,largestRectangleArea(heights));}return max;}// 84. 求柱狀圖最大矩陣面積publicintlargestRectangleArea(int[] heights){int res =0;Deque<Integer> stack =newArrayDeque<>();int[] newHeights =newint[heights.length +2];for(int i =1; i < heights.length +1; i++){newHeights[i]= heights[i -1];}for(int i =0; i < newHeights.length; i++){while(!stack.isEmpty()&& newHeights[stack.peek()]> newHeights[i]){int index = stack.pop();int l = stack.peek();int r = i;res =Math.max(res,(r - l -1)* newHeights[index]);}stack.push(i);}return res;}}
二刷
思路還是記得的
classSolution{publicintmaximalRectangle(char[][] matrix){if(matrix ==null|| matrix.length ==0)return0;int[] heights =newint[matrix[0].length];int res =0;// 逐行轉換for(int i =0; i < matrix.length; i++){// 當前行的逐列維護for(int j =0; j < matrix[0].length; j++){if(matrix[i][j]=='1'){heights[j]++;}else{heights[j]=0;}}res =Math.max(res,largestRectangleArea(heights));}return res;}publicintlargestRectangleArea(int[] heights){int[] newHeights =newint[heights.length +2];for(int i =1; i <= heights.length; i++){newHeights[i]= heights[i -1];}Deque<Integer> stack =newArrayDeque<>();int max =0;for(int i =0; i < newHeights.length; i++){while(!stack.isEmpty()&& newHeights[i]< newHeights[stack.peek()]){int now = stack.poll();int left = stack.peek();int right = i; max =Math.max(max,(right - left -1)* newHeights[now]);}stack.push(i);}return max;}}