標籤:turn com scan 多選 port ring tin UI 多個
一、題目要求:
輸入一個一維整形數組,數組裡有正數也有負數。
一維數組首尾相接,像個一條首尾相接帶子一樣。
數組中連續的一個或多個整數組成一個子數組,每個子數組都有一個和。求所有子數組的和的最大值。
發表一篇部落格文章講述設計思想,出現的問題,可能的解決方案(多選)、原始碼、結果、總結。
二丶設計思想:
遍曆數組裡面的每一個數將第一個數變為最後一個數,具體演算法 a[i-1]=a[i],這樣又變成了一個新的一維數組,輸出每個數組的最大子數組和,然後比較每個輸出的和,找出最大的數
三丶代碼
import java.util.Scanner; public class shuzu { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan=new Scanner(System.in); System.out.print("請輸入數組中數位個數:"); int n=scan.nextInt(); int[] a=new int [n]; System.out.print("請輸入數組:"); for(int i=0;i<n;i++) { a[i]=scan.nextInt(); } int a1=zuida(a,n); int b,temp,i,sum=0; for(b=1;b<n;b++) { temp=a[0]; for(i=1;i<=n-1;i++) { a[i-1]=a[i]; } a[n-1]=temp; if(zuida(a,n)>=sum) { sum=zuida(a,n); } } int a2=sum; if(a1>=a2) { System.out.println("最大子數組和:" + a1); } else { System.out.println("最大子數組和:" + a2); } } public static int zuida(int a[],int n) { int sum=0; int b=0; for(int i=0; i<n; i++) { if(b<0) b=a[i]; else b+=a[i]; if(sum<b) sum=b; } return sum; }}
四丶運行
java (數組)