"Design Ideas"
1. User initializes an array
2. Define Tempmax as a temporary maximum value, define MAX, initial array[0]
3. Use the loop from array[1] to determine whether the Tempmax value is positive or negative, if the positive tempmax is positive, the Tempmax value becomes Tempmax plus the number of traversal, if the Tempmax value is negative, the Tempmax value becomes the traversed number.
4. Compare Max and Tempmax value sizes, if Max teenager Tempmax value is assigned to Max
"Program source Code"
ImportJava.util.*; Public classMaxsarray { Public Static voidMain (String args[]) {Scanner SC=NewScanner (system.in); System.out.println ("Please enter the length of the array you want the maximum value of the Subarray:"); intLength =Sc.nextint (); intArray[] =New int[length]; System.out.println ("Please enter the number of arrays that you want to have the maximum value of the sub-array:"); for(inti=0;i<length;i++) {Array[i]=Sc.nextint (); } intmax = Array[0]; intTempmax = array[0]; for(inti=1;i<length;i++) { if(tempmax<0) {Tempmax=Array[i]; } Else{Tempmax+=Array[i]; } if(tempmax>max) {Max=Tempmax; }} System.out.println ("The maximum number of sub-arrays is:" +max); }}
Results
"Error occurred"
No previous setting Tempmax, if Max value is positive, the output is wrong when the Traverse number is negative
"Solutions"
Adding Tempmax and Max values for comparison
Summary
The traversal sum makes the problem easy to solve, so choosing a good algorithm is very important for a program implementation.
Introduction to Software Engineering-after-school assignment 3 (sub-array for maximum value)