Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
Difficulty: Hard
Solution: http://www.programcreek.com/2014/05/leetcode-maximal-rectangle-java/
public class Solution {
public int helper(int[] height){
Stack<Integer> stack = new Stack<Integer>();
int i = 0, ans = 0;
while(i < height.length){
if(stack.isEmpty() || height[i] >= height[stack.peek()]){
stack.push(i);
i++;
}
else{
int temp = stack.pop();
ans = Math.max(ans, height[temp] * (stack.isEmpty() ? i : i - stack.peek() - 1));
}
}
return ans;
}
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
if(m == 0) return 0;
int n = matrix[0].length;
int ans = 0;
int[][] nums = new int[m][n + 1];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i == 0 && matrix[i][j] == '1'){
nums[i][j] = 1;
}
else if(matrix[i][j] == '1'){
nums[i][j] = 1 + nums[i-1][j];
}
}
}
for(int i = 0; i < m; i++){
ans = Math.max(ans, helper(nums[i]));
}
return ans;
}
}