题目:
返回一个二维整数数组中最大子数组的和。
要求:
输入一个二维整形数组,数组里有正数也有负数。
二维数组首尾相接,象个一条首尾相接带子一样。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。
(1)代码:
1 package test4; 2 3 import java.util.Random; 4 import java.util.Scanner; 5 6 public class Test { 7 8 /** 9 * @param args 10 */ 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 System.out.println("请输入数组的行数和列数:"); 14 Scanner sc=new Scanner(System.in); 15 int n=sc.nextInt(); 16 int m=sc.nextInt(); 17 int w=n*(n-1)/2; 18 int a[][]=new int[n+w][m]; 19 int S=0; 20 Random rand=new Random(); 21 int i=0; 22 int e=0; 23 int y=0; 24 System.out.print("请输入数字范围:"); 25 int m1=sc.nextInt(); 26 int m2=sc.nextInt(); 27 28 for(i=0;i<n;i++) 29 { 30 for(e=0;e<m;e++) 31 { 32 a[i][e]=(int) (m1+Math.random()*(m2-m1+1)); 33 System.out.print(a[i][e]+" "); 34 } 35 System.out.println(); 36 } 37 int MAX=a[0][0]; 38 for(i=n;i<n+w;i++) 39 { 40 for(int j=0;j<m;j++) 41 { 42 a[i][j]=0; 43 } 44 } 45 46 for(int j=0;j<n+w;j++) 47 { 48 array(a,m,j); 49 } 50 for(i=0;i<n;i++) 51 { 52 for(e=1;e<n-i;e++) 53 { 54 for(int x=0;x<m;x++) 55 { 56 if(e==1) 57 { 58 a[n+y][x]=a[i][x]+a[i+1][x]; 59 } 60 else 61 { 62 a[n+y][x]=a[n+y-1][x]+a[i+e][x]; 63 } 64 } 65 y++; 66 } 67 } 68 for(int n1=0;n1<n+w;n1++) 69 { 70 for(int n2=0;n2<m;n2++) 71 { 72 S=S+a[n1][n2]; 73 if(MAX<=S) 74 { 75 MAX=S; 76 } 77 if(MAX<0) 78 { 79 S=0; 80 } 81 } 82 S=0; 83 } 84 System.out.println("和最大子数组值为:"+MAX); 85 } 86 87 static void array(int a[][],int m,int j) //把数组第一个数放到最后,重新排列数组 88 { 89 int q=a[j][0]; 90 for(int i=0;i<m-1;i++) 91 { 92 a[j][i]=a[j][i+1]; 93 } 94 a[j][m-1]=q; 95 } 96 } 97
(2)截图:
![](https://images0.cnblogs.com/blog2015/717953/201504/221317166406375.png)
![](https://images0.cnblogs.com/blog2015/717953/201504/221317296099379.png)
(3)设计思路:
增加数组的行数保存两行或几行的数组的和,形成一个新的二维数组,在利用求一维数组的最大子数组和的方法,将数组中第一个数放在数组最后一个并循环此方法,在求最大数时,对每行数组最大值都进行比较,利用MAX实现记录和比较