思路与这边文章一致:
https://blog.csdn.net/zhumingyuan111/article/details/80192729
因为是二维数组可以做一个预处理,可以使得在O(1)的时间复杂度获得到Array[low..hight][col]的值。
下面给出代码
public void getMaxSubArray(int[][]array){
int row = array.length;
int width = array[0].length;
int[][] fe = new int[row+1][width+1];
for(int i=1;i<=row;i++){
for(int j=1;j<=width;j++){
fe[i][j] = fe[i][j-1] + fe[i-1][j] - fe[i-1][j-1] + array[i-1][j-1];
}
}
int finalMax =0,finalLow = -1,finalHigh = -1,finalB = -1,finalE = -1;
for(int low=0;low<row;low++){
for(int high=low+1;high<=row;high++){
int max = 0,sum = 0,b=-1,bt=-1,e=-1;
for(int j=1;j<=width;j++){
sum += getValue(fe,low,high,j);
if(sum>max){
max = sum;
e = j - 1;
b = bt;
}
if(sum<0){
sum = 0;
bt = j - 1;
}
}
if(max>finalMax){
finalMax = max;
finalB = b;
finalE = e;
finalHigh = high-1;
finalLow = low-1;
}
}
}
for(int i=finalLow+1;i<=finalHigh;i++){
for(int j=finalB+1;j<=finalE;j++){
System.out.print(array[i][j]+ ",");
}
System.out.println("");
}
}
public int getValue(int[][]fe,int low,int high,int col){
return fe[high][col] - fe[low][col] - fe[high][col-1] + fe[low][col-1];
}
public static void main(String[]args){
MaxSubArrayII arrayII = new MaxSubArrayII();
arrayII.getMaxSubArray(new int[][]{
{1,-10,-11},
{4,-95,6},
{7,8,9}
});
}