510. Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
RETURN 6
class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int rows = matrix.length;
int cols = matrix[0].length;
int[][] height = new int[rows][cols];
for (int j = 0; j < cols; j++) {
height[0][j] = (matrix[0][j] == '1') ? 1 : 0;
}
for (int i = 1 ; i < rows ;i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == '1') {
height[i][j] = height[i-1][j] + 1;
}else{
height[i][j] = 0;
}
}
}
int ans = 0;
for (int i = 0; i < rows; i++) {
int area = maxAreainHisto(height[i]);
ans = Math.max(ans, area);
}
return ans;
}
public int maxAreainHisto(int[] height) {
Stack<Integer> stack = new Stack<>();
int area = 0;
for (int i = 0; i <= height.length; i++) {
if (i <height.length ) {
System.out.println(height[i]);
}
int curt = (i == height.length) ? -1 : height[i];
while(!stack.isEmpty() && curt <= height[stack.peek()] ) {
int h = height[stack.pop()];
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
area = Math.max(area, w * h);
}
stack.push(i);
}
return area;
}
}