It's not a easy problem, yet if you've done "Largest Rectangle in Histogram", one approach is convert to that problem for each row, and get "largest rectangle in histogram" for each row, and compare each row's "largest rectangle" to get maximal rectangle in the matrix.
That for heights[i][j] it stands for, for i-th row, the height at column j, thus each row in heights[i][j] could just be input
for the function int largestRectangleArea(int[] heights).
At this moment, the "Maximal Rectangle" problem has been converted to a series of "Largest Rectangle in Histogram" problem.
O(n\*m) time, O(n\*m) space
Solution
Convert to Largest Rectangle in Histogram problem (where DP is used) - 13 ms, faster than 70.66%
classSolution {publicintmaximalRectangle(char[][] matrix) {if (matrix ==null||matrix.length==0|| matrix[0].length==0) return0;int rowLength =matrix.length;int colLength = matrix[0].length;int[][] heights =newint[rowLength][colLength];for (int i =0 ; i < rowLength; i++) {for (int j =0; j < colLength; j++) {if (matrix[i][j] =='1') {if (i ==0) heights[i][j] =1;if (i >0) heights[i][j] = heights[i-1][j] +1; } else { heights[i][j] =0; } } }int max =0;for (int[] hs : heights) { max =Math.max(max,largestRectangleArea(hs)); }return max; }publicintlargestRectangleArea(int[] heights) {if (heights ==null||heights.length==0) {return0; }if (heights.length==1) {return heights[0]; }int maxArea =0;int[] leftBound =newint[heights.length];int[] rightBound =newint[heights.length]; leftBound[0] =-1; rightBound[heights.length-1] =heights.length;for (int i =1; i <heights.length; i++) {int l = i -1;while (l >=0&& heights[l] >= heights[i]) { l = leftBound[l]; } leftBound[i] = l; }for (int i =heights.length-2; i >=0; i--) {int r = i +1;while (r <heights.length&& heights[r] >= heights[i]) { r = rightBound[r]; } rightBound[i] = r; }for (int i =0; i<heights.length; i++) { maxArea =Math.max(heights[i] * (rightBound[i] - leftBound[i] -1), maxArea); }return maxArea; } }
Convert to largest rectangle histogram (where monotonous stack is used) - (35 ms AC)