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

被折叠的 条评论
为什么被折叠?



