Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
代码
Approach #1 Brute Force
Trivially we can enumerate every possible rectangle. This is done by iterating over all possible combinations of coordinates (x1, y1) and (x2, y2) and letting them define a rectangle with the coordinates being opposite corners. This is too slow to pass all test cases.
Time: O(N^3)Space: O(1)
publicclassSolution {publicintlargestRectangleArea(int[] heights) {int maxarea =0;for (int i =0; i <heights.length; i++) {for (int j = i; j <heights.length; j++) {int minheight =Integer.MAX_VALUE;for (int k = i; k <= j; k++) minheight =Math.min(minheight, heights[k]); maxarea =Math.max(maxarea, minheight * (j - i +1)); } }return maxarea; }}
classSolution {publicintmaximalRectangle(char[][] matrix) {if (matrix.length==0) return0;int R =matrix.length;int C = matrix[0].length;int maxarea =0;int[][] dp =newint[R][C];for (int i =0; i < R; i++) {for (int j =0; j < C; j++) {if (matrix[i][j] =='1') {if (j ==0) { dp[i][j] =1; } else { dp[i][j] = dp[i][j -1] +1; }int width = dp[i][j];for (int k = i; k >=0; k--) { width =Math.min(width, dp[k][j]); maxarea =Math.max(maxarea, width * (i - k +1)); } } } }return maxarea; }}
Approach #3 Using Histograms - Stack
Time complexity: O(n)
Space complexity: O(n)
转化成 Leetcode 84 的单调递增栈
classSolution {publicintmaximalRectangle(char[][] matrix) {if (matrix.length==0) return0;int maxarea =0;int[] dp =newint[matrix[0].length];for (int i =0; i <matrix.length; i++) {for (int j =0; j < matrix[0].length; j++) {// update the state of this row's histogram using the last row's histogram// by keeping track of the number of consecutive ones dp[j] = matrix[i][j] =='1'? dp[j] +1:0; }// update maxarea with the maximum area from this row's histogram maxarea =Math.max(maxarea,leetcode84(dp)); } return maxarea; }// Get the maximum area in a histogram given its heightspublicintleetcode84(int[] heights) {Stack <Integer> stack =newStack<>();stack.push(-1);int maxarea =0;for (int i =0; i <heights.length; ++i) {while (stack.peek() !=-1&& heights[stack.peek()] >= heights[i]) { maxarea =Math.max(maxarea, heights[stack.pop()] * (i -stack.peek() -1)); }stack.push(i); }while (stack.peek() !=-1) { maxarea =Math.max(maxarea, heights[stack.pop()] * (heights.length-stack.peek() -1)); }return maxarea; }}
Approach #4 Dynamic Programming - Maximum Height at Each
Complexity Analysis
Time complexity : O(NM). In each iteration over N we iterate over M a constant number of times.
Space complexity : O(M). M is the length of the additional arrays we keep.