【题目】
给定一个矩阵matrix,其中的值有正负0,返回子矩阵的最大累加和。
【举例】
例如,matrix为:
-90 48 78
64 -40 64
-81 -7 66
其中,最大累加和的子矩阵为:
48 78
-40 64
-7 66
所以返回209
matrix为:
-1 -1 -1
-1 2 2
-1 -1 -1
其中,最大累加和的子矩阵为:
2 2
所以返回累加和4
【代码】
public static void main(String[] args) {
int[][] arr={{-,,},{,-,},{-,-,}};
System.out.println(maxSum(arr));//209
int[][] arr1={{-,-,-},{-,,},{-,-,-}};
System.out.println(maxSum(arr1));//4
}
//子矩阵的最大累加和问题
public static int maxSum(int[][] m){
if(m==null||m.length==||m[].length==){//判断矩阵非空
return ;
}
int[] s=null;//累加数组
int cur=;
int max=Integer.MIN_VALUE;
for(int i=;i!=m.length;i++){//从第i行元素开始,往下查找所有子矩阵
s=new int[m[].length];
for(int j=i;j!=m.length;j++){
cur=;
for(int k=;k!=m[].length;k++){
s[k]+=m[j][k];//每一步的累加数组(叠加每一列)
cur+=s[k];
max=Math.max(cur, max);//每一步的最大子矩阵的累加和
cur=cur>?cur:;
}
}
}
return max;
}