3. Find the maximum and large array of sub-arrays
Topic:
Enter an array of shapes with positive and negative numbers in the array.
One or more consecutive integers in an array make up a sub-array, each of which has a and.
The maximum value for the and of all sub-arrays. Requires a time complexity of O (n).
For example, the input array is 1,-2, 3, 10,-4, 7, 2,-5, and the largest subarray is 3, 10,-4, 7, 2,
So the output is the and 18 of the subarray.
Idea: Use the auxiliary variable Max to record the maximum sum of the subarray, and to begin the traversal from the array header, if the array element is a negative number with the sum of the previous sum, reset the sum result to zero, otherwise the resulting sum value will be compared to max if it is less than Max, and the next element of the array continues to be evaluated
1 PackageCom.rui.microsoft;2 3 Public classTest03_maxsubarray {4 5 Public Static voidMain (string[] args) {6 int[] Array = {1,-2, 3, 10,-4, 7, 2,-5};7 System.out.println (Findmax (array));8 }9 Ten Private Static intFindmax (int[] Array) { One intres = 0; A intMax =Res; - - for(inti = 0; i < Array.Length; i++){ theRes + =Array[i]; - if(Res >max) { -Max =Res; -}Else if(Res < 0){ +res = 0; - Continue; + } A at } - - returnMax; - } -}
Microsoft algorithm 100 question 03 to find the largest and the sub-array