今天做出一维数组的最大子数组的回调查询,我先是循环输出了每个数组的和及最大数组,最后输入回调查询,代码如下:
package mypackage; import java.util.Scanner; public class e { public static int max(int a[],int n) //判断大小 { int x=a[0]; for(int i=0;i<=n;i++) { if(a[i]>x) {x=a[i];} } return x; } public static int add(int a[],int i,int j) //加和 { int x=a[i],p; for(p=i+1;p<=j;p++) { x=a[p]+x; } return x; } public static int d1(int a[],int n) { int i=0,j,b,c=0; int []x=new int[1000]; for(i=0;i<=n-1;i++) { for(j=n-1;j>=i;j--) { x[c]=add(a,i,j); int m=i+1,h=j+1; c++; System.out.println("第"+c+"个数组:"+"第"+m+"个元素至第"+h+"个元素,和为"+add(a,i,j)); System.out.println("最大值为:"+max(x,c-1)); System.out.print("\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } return max(x,c); } public static int d2(int a[],int n,int o) { int i=0,j,b,c=0; int []x=new int[1000]; for(i=0;i<=n-1;i++) { for(j=n-1;j>=i;j--) { x[c]=add(a,i,j); int m=i+1,h=j+1; c++; if(c>=o) { System.out.println("第"+c+"个数组:"+"第"+m+"个元素至第"+h+"个元素,和为"+add(a,i,j)); System.out.println("最大值为:"+max(x,c-1)); System.out.print("\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } return max(x,c); } public static void main(String[] args) { int []a=new int[1000]; Scanner sc = new Scanner(System.in); System.out.println("请输入个数:"); int x=sc.nextInt(); for(int i=0;i<=x-1;i++) { if((int)(Math.random()*(2-1+1))==1) { a[i]=(int)(Math.random()*(1000-1+1)); System.out.print(a[i]+"\t"); }else { a[i]=-(int)(Math.random()*(1000-1+1)); System.out.print(a[i]+"\t"); } } System.out.println("\n"); System.out.println("最大值为:"+d1(a,x)); System.out.println("\n会调至:"); Scanner sc1 = new Scanner(System.in); int y=sc1.nextInt(); System.out.println("最大值为:"+d2(a,x,y)); } }