題目:
給任意一個整數數組,找出這個數組的和最大的連續子數組(子數組的和最大且子數組連續)。要求:算法的時間復雜度為O(n)。
程序設計思想:
1:用maxValue記錄當前連續子數組和為最大的和的值,初始化其值為:maxValue=a[0]。注:記數組為a[n]。
2:這個過程總的思想就是,從數組頭開始往后,每次加進一個值,它們的和記為tempValue,若tempValue比新加進來的數值本身要小,應該從這個位置開始重新開始計算tempValue的值。而每次的tempValue都應該和maxValue作比較,若tempValue更大,則應更新maxValue的值為tempValue的值,相對的maxValue對應的子數組也要變成tempValue對應的子數組。這樣下來,到最后將數組完全掃描一遍之后,就能得到最大和的連續子數組以及其和maxValue。這樣的時間復雜度正好是O(n)。
3:執行for循環:for(i=1;i<n;i++)。循環體內容為:用tempValue記錄當前tempValue同數組中下一個值的和即令:tempValue=tempValue+a[i],初始化其值為:tempValue=a[0]。更新tempValue的值之后,若tempValue小於或等於a[i],則應舍棄目前tempValue對應的子數組,使其重新對應一個新數組,應該使tempValue對應的子數組首尾都指向a[i]。而若tempValue大於a[i]且tempValue大於maxValue,則更新maxValue對應的子數組,令其對應的子數組變成tempValue對應的子數組。這些工作做完后,繼續下一次循環。
源程序代碼:
import java.util.Scanner; public class Second { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("輸入數組長度"); int n=sc.nextInt(); System.out.println("輸入數組數據(用空格分開)"); int i; int a[]=new int[n]; for(i=0;i<n;i++) a[i]=sc.nextInt(); int begin=0;//子數組開始下標 int end=0;//子數組結束下標 int maxValue=a[0]; int tempValue=maxValue; //for循環尋找最大和的連續子數組 for(i=1;i<n;i++) { tempValue+=a[i]; if((tempValue>a[i])&&(tempValue>maxValue)) { end=i; maxValue=tempValue; } else if(tempValue<=a[i]) { begin=i; end=i; tempValue=a[i]; } } //輸出最大和的連續子數組的相關信息 System.out.println("最大子數組和為:"+maxValue+"\n子數組內容為:"); System.out.println("下標:"); for(i=begin;i<=end;i++) System.out.print(i+" "); System.out.println("\n"+"下標對應數值:"); for(i=begin;i<=end;i++) System.out.print(a[i]+" "); } }
運行結果截圖: