首先来确定子数组的起点和终点,确定上下界,然后用FOR循环遍历每次能确定的所有子数组,转换成一维数组求出子数组和
package 二维数组求最大子数组和;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String args[]) throws IOException {
File f1 = new File("input.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb1 = new StringBuilder();
String hasRead;
while((hasRead=br.readLine())!=null){
sb1.append(hasRead+" ");
}
String text = sb1.toString();
String[] textArray = text.split(" ");
int[][] a = new int[5][5];
int cow,i,maxValue;
int m=0;
int[] sum = new int[50];
int max=0;
int j = 0;
for( i=0;i<5;i++)
{
for(cow=0;cow<5;cow++)
{
a[i][cow] = Integer.valueOf(textArray[j]);
j++;
}
}
maxValue=a[0][0];
for(i=0;i<5;i++)
{
while(m+i<5)
{
for(cow=0;cow<5;cow++)
{
sum[cow]=sum[cow]+a[m+i][cow];
}
max=0;
for(cow=0;cow<5;cow++)
{
if(max+sum[cow]>sum[cow])
{
max=max+sum[cow];
}
else
{
max=sum[cow];
}
if(max>maxValue)
{
maxValue=max;
}
}
m++;
}
m=0;
for(cow=0;cow<5;cow++)
{
sum[cow]=0;
}
}
System.out.println("最大子数组和为:"+maxValue);
}
}
运行截图: