我写的java code O(m*m*n) 实现:
本质上跟max sub-matrix sum 差不多,就是把二维问题转化为一维。
public int getSubMatrixWithEqual0And1(int[][] matrix) {
int m, n;
if(matrix == null || (m = matrix.length) == 0 || (n = matrix[0].
length) == 0) {
return 0;
}
int overallMax = 0;
for(int i = 0; i < m; i++) {
int[] rowSum = new int[n];
for(int j = i; j < m; j++) {
for(int k = 0; k < n; k++) {
rowSum[k] += matrix[j][k] == 0 ? -1 : 1;
}
int maxSofar = (j-i+1) * getMaxLenWithEqual0And1(rowSum);
if(maxSofar > overallMax) {
overallMax = maxSofar;
}
}
}
return overallMax;
}
private int getMaxLenWithEqual0And1(int[] arr) {
int n = arr.length;
int[] leftSum = new int[n];
Map map = new HashMap();
int max = 0;
for(int i = 0; i < n; i++) {
leftSum[i] = i == 0 ? arr[i] : leftSum[i-1]+arr[i];
if(leftSum[i] == 0) {
max = i+1;
}
if(map.containsKey(leftSum[i])) {
int len = i - map.get(leftSum[i]);
if(len > max) {
max = len;
}
} else {
map.put(leftSum[i], i);
}
}
return max;
}