連續子陣列的最大和Java實現
阿新 • • 發佈:2018-12-23
問題描述:
一個數組有 N 個元素,求連續子陣列的最大和。 例如:[-1,2,1],和最大的連續子陣列為[2,1],其和為 3
本文采用的是陣列,利用等差數列進行求和,程式碼如下:
package series00; import java.util.Arrays; import java.util.Scanner; public class series1 { public static void main(String[] args) { //準備資料 System.out.println("請輸入個數N:"); Scanner sc1=new Scanner(System.in); int N=sc1.nextInt(); System.out.println("請輸數列:"); int[] a=new int[N]; for (int i = 0; i < a.length; i++) { Scanner sc2=new Scanner(System.in); a[i]=sc2.nextInt(); } int count=0; int m=0; int[] sum=new int[N-2]; for (int i = 0; i < a.length-2; i++) { //判斷是否連續 if (((a[i]-a[i+1]==-1&&a[i+1]-a[i+2]==-1)) ||((a[i]-a[i+1]==1)&&a[i+1]-a[i+2]==1)){ count++; }else if(count!=0) { //等差數列求和 if (count%2==0) { sum[m]=((count+2)/2)*(a[i-count]+a[i+1]); }else { sum[m]=(count+2)*(a[i-1]); } count=0; m++; }else { count=0; } if ((i==a.length-3)&&(count!=0)) { if (count%2==0) { sum[m]=((count+2)/2)*(a[i-count]+a[i+1]); }else { sum[m]=(count+2)*(a[i-1]); } } } System.out.println(Arrays.toString(sum)); Arrays.sort(sum); System.out.println("連續子陣列的最大和為:"+sum[N-3]); } }
進行測試:
請輸入個數N:
20
請輸數列:
1
2
3
4
5
6
5
4
3
2
3
4
5
6
7
6
5
4
3
2
結果:
[21, 20, 27, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
最大連續和為:27