对一维数组随机一段求和求最大
package shuzi; import java.util.Scanner; public class Suzi { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入输入数字的个数"); Scanner sc = new Scanner(System.in); int n,i; n=sc.nextInt(); System.out.println("请输入输入"+n+"数字"); int[] a = new int[n]; for(i=0;i<n;i++) { a[i]=sc.nextInt(); } for(i=1;i<n;i++) { if(a[i]+a[i-1]>a[i]) a[i]=a[i]+a[i-1]; } int ans=-100000; for(i=0;i<n;i++) { if(ans<a[i]) { ans=a[i]; } } System.out.println("最大的数为"+ans); } }
对循环的一维数组进行求和,每个值只用一次
package shuzi; import java.util.Scanner; public class Suzi { public static void main(String args[]) { Scanner scan=new Scanner(System.in); System.out.println("请输入个数"); int n=scan.nextInt(); int [] a=new int [n]; int [] b=new int [n]; int i,j = 0,k = 0; System.out.println("请输入数字"); for(i=0;i<n;i++) { a[i]=scan.nextInt(); b[i]=a[i]; } for(i=1;i<n;i++) { if(a[i]+a[i-1]>a[i]) { a[i]=a[i]+a[i-1]; j=i; }else { k=i; } } for(i=j+1;i<n;i++) { a[i]=a[i]+a[i-1]; } for(i=0;i<k;i++) { if(a[n-1]+b[i]>a[n-1]) { a[n-1]=a[n-1]+b[i]; } } int ans=-100000; for(i=0;i<n;i++) { if(ans<a[i]) { ans=a[i]; } } System.out.println(ans); } }