85. Maximal Rectangle
原创
©著作权归作者所有:来自51CTO博客作者wx62ea2466cca9a的原创作品,请联系作者获取转载授权,否则将追究法律责任
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) {
int m = matrix.length;
if(matrix == null || m == 0)
return 0;
int n = matrix[0].length;
int maxA = 0;
int[] right = new int[n], left = new int[n], heights = new int[n]; // rectangle with highest height
Arrays.fill(right,n);
for(int i=0; i<m; i++) {
int curleft = 0, curright = n;
for(int j=0; j<n; j++) {
if(matrix[i][j] == '1')
heights[j]++;
else
heights[j] = 0;
}
for(int j=0; j<n; j++) {
if(matrix[i][j] == '1')
left[j] = Math.max(curleft, left[j]); // each i has own left[], each will renew
else {
left[j] = 0;
curleft = j + 1;
} // most next positon to zero
}
for(int j=n-1; j>=0; j--) {
if(matrix[i][j] == '1')
right[j] = Math.min(curright, right[j]);
else {
right[j] = n;
curright = j;
} // remain at last zero position
}
for(int j=0; j<n; j++) {
maxA = Math.max(maxA, (right[j] - left[j]) * heights[j]);
}
}
return