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.
Java代码:
public class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length==0)return 0;
int[] left=new int[matrix[0].length],right=new int[matrix[0].length];
int[] hight=new int[matrix[0].length];
int max=0;
for(int i=0;i<matrix[0].length;i++){
left[i]=0;
right[i]=matrix[0].length-1;
}
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++)
if(matrix[i][j]=='1')hight[j]=hight[j]+1;
else hight[j]=0;
left[0]=0;
int cur_left=matrix[i][0]=='1'? 0:1;
for(int j=1;j<matrix[0].length;j++)
if(matrix[i][j]=='1')left[j]=Math.max(left[j],cur_left);
else{
left[j]=0;
cur_left=j+1;
}
right[matrix[0].length-1]=matrix[0].length-1;
int cur_right=matrix[i][matrix[0].length-1]=='1'? matrix[0].length-1:matrix[0].length-2;
for(int j=matrix[0].length-2;j>=0;j--)
if(matrix[i][j]=='1')right[j]=Math.min(right[j],cur_right);
else {
cur_right=j-1;
right[j]=matrix[0].length-1;
}
for(int j=0;j<matrix[0].length;j++){
max=Math.max(max,(right[j]-left[j]+1)*hight[j]);
//System.out.print(max+" ");
}
}
return max;
}
}
时间复杂度:O(n^2)