I. Design ideas
First the maximum Subarray maxsum and the start position value Maxstart are the first elements of the array, then the value of the starting position, if Maxstart is less than 0, the other Maxstart equals 0, and then Maxstart adds the next array element on its own basis. Again determine the size of the Maxstart and Maxsum, if the Maxstart is greater than maxsum, then the value of Maxsum is the value of maxstart,maxstart unchanged; recursively until the last element of the array, The last Maxsum value is the number of the largest subarray in the array.
Two. Problems that arise
1. At first, there is no record of the starting position value, just to determine the next value of positive and negative, positive plus, negative skip, resulting in the sub-array is not continuous;
2. The value of the starting position is changed, the positive sub-array and the maximum value plus the next array element, the negative sub-array and the maximum value becomes the value of the next array element, this time can solve the problem of the beginning, but if the last element of the array is negative, it will be added to the sub-array and, What's more, if the elements of the array are all negative, the final result is the last element.
Three. Solution
Define variables for the maximum subarray and the values at the start position, and let the start position values participate in the loop, updating the maximum subarray and values after each loop until the loop ends.
Four. Source code
PackageSub-array;ImportJava.util.Scanner; Public classArrayMax { Public Static voidMain (string[] args) {intNumber,maxsum,maxstart; inti; Scanner in=NewScanner (system.in); System.out.println ("Please enter the size of the array:"); number=In.nextint (); intarray[]=New int[number]; System.out.println ("Please enter the value of the array:"); for(i=0;i<number;i++) {Array[i]=In.nextint (); } maxsum=array[0]; Maxstart=array[0]; for(i=1;i<number;i++) { if(maxstart<0) {Maxstart=0; } Maxstart+=Array[i]; if(maxstart>maxsum) Maxsum=Maxstart; } System.out.println (Maxsum); In.close (); }}
Five. Results
Six. Summary
In considering this problem, first of all, do not think about the overall how, first, from the beginning of the elements to consider, and then gradually expand, the loop recursion is just the beginning of the situation can be.
Returns the maximum number of sub-arrays in an integer array and