First, the topic requirements
1. Enter an integer array with positive and negative numbers in the array.
2. One or more integers in the array make up a sub-array, each of which has a and.
3. Ask for the maximum value of all sub-arrays. Requires a time complexity of O (n).
Second, the design idea
1. First randomly generates an array with positive and negative numbers.
2. Start with the first element in the array a[0], and then calculate the value of a[0], a[0]+a[1], A[0]+a[1]+...+a[i], and the and of each sub-array starting from a[0], and remove the maximum value.
3. Start with the second element of the array, a[1], and then calculate the number of each sub-array and remove the maximum. Loop until the last element of the array, remove a[i].
4. Compare all the sub-arrays and derive the maximum value.
Third, the program code
//xueqing Lu Yu//Date: March 18, 2015 PackageCom.java.lianxi;ImportJava.util.*; Public classLianxi2 { Public Static voidMain (string[] args) {Scanner input=NewScanner (system.in); System.out.print ("Please enter the number of numbers in the array:"); intnum=Input.nextint (); intarray[]=New int[num]; for(inti=0;i<num;i++) { if((int) (Math.random () * *) ==0) {Array[i]=(int) (Math.random () *10); } Else{Array[i]=-(int) (Math.random () *10); } } for(inti=0;i<num;i++) {System.out.println (array[i]); } intMax=0; intlist[]=New int[num]; for(intj=0;j<num;j++) {Max=Array[j]; intSum=0; for(intt=j;t<num;t++) {sum=sum+Array[t]; if(sum>max) {Max=sum; }} List[j]=Max; } for(inti=0;i<num;i++) {System.out.print (The maximum value of the number of sub-arrays for "+ (i+1) +" Second comparison is: "); System.out.println (List[i]); } for(inti=1;i<num;i++) {Max=list[0]; if(list[i]>max) {Max=List[i]; }} System.out.print ("The maximum number of sub-arrays and is:" +max); }}
Iv. Results of the experiment
V. Experience of experiment
In this procedure, the summation takes the maximum value to the loop nesting, the time complexity request did not reach. When you encounter a problem, analyze the code that is executed each time the loop completes the purpose.
This pair development, I am responsible for the program analysis, design good ideas, xueqing is mainly responsible for writing code, the process encountered problems, we two joint solution.
Pair development--Returns the maximum number of sub-arrays in an integer array and