Description
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle.
As an example, the maximal sub-rectangle of the array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:
9 2
-4 1
-1 8
and has a sum of 15.
描述为英语,大概意思就是求一个N*N的矩阵的最大子矩阵和
无从下手,看了一些大佬们的代码思路,学习了降维思想。可以讲二维多行合并成一行降成一维。
我们先求一维数组的最大子数组和。思路如下:其实就是动态规划
假如之前累加的结果大于零,则继续累加。否则从下一个位置开始累加。每次判断是否是最大值。即是
temp=max(temp, temp+m[i](if(temp>0)) )
求一维数组最大累加和代码如下
package com.luo;
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
while(in.hasNextInt()){
int len=in.nextInt();
int[] input=new int[len];
for(int i=0;i<len;i++){
input[i]=in.nextInt();
}
int max=0;
int temp=0;
for(int i=0;i<len;i++){
if(temp>0)
temp+=input[i];
else
temp=input[i];
if(temp>max)
max=temp;
}
System.out.println("最大字段和为:"+max);
}
}
}
如何将一维拓展到二维呢。多行合并成一行。要进行合并的行数很多,两行合并成一行,三行合并成一行,四行合并成一行... 这样子不会造成数据重叠吗。
其实这是可以避免的,我们从第一行开始,这时候需要将第一行第二行合并成一行计算最大矩阵,接着合并第一二三行计算最大矩阵,再接着合并第一二三四行计算最大矩阵... 合并完所有包括第一行的矩阵后第一行被合并的情况已经被全部考虑了,这时候不需要第一行了
所以代码如下:
package com.luo.daily;
import java.util.Scanner;
public class Poj1050 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
while(in.hasNextInt()){
int N=in.nextInt();
int[][] input=new int[N][N];
int max=0;
int temp=0;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
input[i][j]=in.nextInt(); //输入顺便计算每行的最大子数组和
if(temp>0)
temp+=input[i][j];
else
temp=input[i][j];
if(temp>max)
max=temp;
}
}
for(int i=0;i<N-1;i++){
for(int j=i+1;j<N;j++){
temp=0;
for(int k=0;k<N;k++){
input[i][k]+=input[j][k];
if(temp>0)
temp+=input[i][k];
else
temp=input[i][k];
if(temp>max)
max=temp;
}
}
}
System.out.println("最大的子矩阵和为:"+max);
}
}
}