Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. Have you been asked this question in an interview? 方法是 largest rectangle in histogram + dp public class Solution { public int maximalRectangle(char[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) { return 0; } int[][] height = getHeight(matrix); Stack<Integer> st = new Stack<Integer>(); int result = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j <= matrix[0].length; j++) { int cur = (j == matrix[0].length ? - 1: height[i][j]); while (!st.empty() && height[i][st.peek()] >= cur) { int l = height[i][st.pop()]; int w = st.empty() ? j: j - st.peek() - 1; result = Math.max(result, w * l); } st.push(j); } //when traverse over one row, remember to pop the last value out //or define the staci inside the second for loop st.pop(); } return result; } int[][] getHeight(char[][] matrix) { int[][] height = new int[matrix.length][matrix[0].length]; for (int i = 0; i < matrix[0].length; i++) { height[0][i] = matrix[0][i] - '0'; } for (int i = 1; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] - '0'== 0) { height[i][j] = 0; } else { height[i][j] = height[i - 1][j] + 1; } } } return height; } }