Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
---
1. O(n^3)
2. 很想84, largest rectangle in histogra,
每一行存以当前行为底的柱状图, 求最大矩形面积。
O(N^2)
---
10/01 YC version
public class Solution { public int maximalRectangle(char[][] matrix) { int rowN = matrix.length; int calN = rowN==0 ? 0 : matrix[0].length; // check if empty matrix int[][] helperMatrix = new int[rowN][calN]; for(int i=0; i<rowN; i++){ for(int j=0; j<calN; j++){ if(i == 0){ if(matrix[i][j] == '1') helperMatrix[i][j] = 1; }else{ if(matrix[i][j] == '1') helperMatrix[i][j] = helperMatrix[i-1][j] + 1; else helperMatrix[i][j] = 0; } } } int maxArea = 0; for(int i=0; i<rowN; i++){ int area = largestRectangleArea(helperMatrix, i); // update if(area > maxArea) maxArea = area; } return maxArea; } public int largestRectangleArea(int[][] matrix, int row) { int maxArea = 0; Stack<Integer> stack = new Stack<Integer>(); int i=0; while(i<matrix[row].length){ if(stack.isEmpty() || matrix[row][stack.peek()] <= matrix[row][i]){ stack.push(i); i++; }else{ // current min height index t int t = stack.pop(); int area = (stack.isEmpty() ? i : i-stack.peek()-1) * matrix[row][t]; // update if(area > maxArea) maxArea = area; } } while(!stack.isEmpty()){ int t = stack.pop(); int area = (stack.isEmpty() ? i : i-stack.peek()-1) * matrix[row][t]; // update if(area > maxArea) maxArea = area; } return maxArea; } }
---
public class Solution { public int maximalRectangle(char[][] matrix) { int m = matrix.length; int n = m == 0 ? 0 : matrix[0].length; int[][] height = new int[m][n + 1];
// (有人说!) //actually we know that height can just be a int[n+1], //however, in that case, we have to write the 2 parts together in row traverse, //which, leetcode just doesn't make you pass big set //leetcode是喜欢分开写循环的,即使时间复杂度一样,即使可以节约空间 int maxArea = 0; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++) { if(matrix[i][j] == '0'){ height[i][j] = 0; }else { height[i][j] = i == 0 ? 1 : height[i - 1][j] + 1; } } } for(int i = 0; i < m; i++){ int area = maxAreaInHist(height[i]); if(area > maxArea){ maxArea = area; } } return maxArea; } private int maxAreaInHist(int[] height){ Stack<Integer> stack = new Stack<Integer>(); int i = 0; int maxArea = 0; while(i < height.length){ if(stack.isEmpty() || height[stack.peek()] <= height[i]){ stack.push(i++); }else { int t = stack.pop(); maxArea = Math.max(maxArea, height[t] * (stack.isEmpty() ? i : i - stack.peek() - 1)); } } return maxArea; } }