標籤:ini 結束 四則運算 system.in 大於 scan start http 題目
題目要求:尋找數組連成環形的和最大的連續子數組
實驗代碼:
1 package zuoYe; 2 3 import java.util.Scanner; 4 5 6 public class MaxSubArray { 7 public static void main(String[] args) { 8 Scanner scan = new Scanner(System.in); 9 10 11 //輸入資料12 System.out.println("請輸入數組長度");13 int n = scan.nextInt();14 int[] a = new int[n];15 16 System.out.println("請輸入數組元素");17 for(int i = 0;i < n;i++)18 {19 a[i] = scan.nextInt();20 }21 scan.close();22 //計算此數組的和最大的連續子數組23 int[] result = maxSub(a,a.length);24 System.out.println("不串連成環的和最大的連續子數組:");25 for(int i = result[0];i <= result[1];i++)26 {27 System.out.print(a[i] + "\t");28 }29 System.out.println("和為:" + result[2]);30 31 32 33 34 //將此數組連成一個環,再計算此數組的和最大的連續子數組35 //連成一個環即將數組後再接上此數組,但是數組的最後一個元素不用接,相當於計算接上之後的數組的和最大子數組36 int[] b = new int[2 * n - 1];37 for(int i = 0;i < n - 1;i++)38 {39 b[i] = a[i];40 b[n + i] = a[i];41 }42 b[n - 1] = a[n - 1];43 int[] result2 = maxSub(b,n);44 System.out.println("\n\n將數組連成環後的和最大的連續子數組:");45 for(int i = result2[0];i <= result2[1];i++)46 {47 System.out.print(b[i] + "\t");48 }49 System.out.println("和為:" + result2[2]);50 51 52 }53 54 55 56 57 //計算a數組的和最大的連續子數組(a數組為連成環後的等價數組,即原數組的二倍,n為原數組的長度)58 public static int[] maxSub(int[] a,int n)59 {60 int an = a.length;//連成環的等價數組的長度61 int currectSum = a[0];//記錄當前累加和,初始值為a[0]62 int currectStartIndex = 0;//記錄當前累加的起始下標,初始值為063 int count = 1;//記錄累加元素的個數,初始值為164 int[] result = new int[3];//記錄結果子數組的資訊,65 result[0] = 0;//結果子數組的開始下標66 result[1] = 0;//結果子數組的結束下標67 result[2] = a[0];//結果子數組的和68 for(int i = 1;i < an;i++)//依次遍曆a數組的每個元素69 {70 if(currectSum <= 0)//如果當前累加和不大於0,不大於0對後續的元素沒有貢獻,可以去掉了,所以應從a[i]處重新開始加71 {72 currectSum = a[i];//將當前累加和賦值為a[i]73 currectStartIndex = i;//將當前累加的開始下標賦值為i74 count = 1;//將累加元素的個數記為175 }76 else//當前累加和大於0,則繼續加a[i]77 {78 currectSum += a[i];79 count++;//當前累加元素的個數加一80 }81 if(currectSum > result[2])//如果當前累加和大於原結果數組的累加和result[2],則應該將結果子數組資訊更新為當前子數組,因為當前子數組的累加和大於結果子數組的和82 {83 result[0] = currectStartIndex;//結果子數組的開始下標為當前子數組的開始下標84 result[1] = i;//結果子數組的結束下標賦值為i85 result[2] = currectSum;//結果子數組的累加和賦值為當前子數組的累加和86 }87 if(count >= n)//如果累加的元素個數等於原數組(未連成環的數組)的長度,則說明已經加了最多的元素,不能再加了,也就是說和最大的子數組即為原數組,應該結束迴圈88 {89 break;90 }91 }92 return result;93 }94 95 96 97 }
實驗:
java-四則運算-四