For an array with n elements, a[0]~a[n-1], the maximum value of the subarray is obtained.
For example: array a[] = [−2, 1,−3, 4,−1, 2, 1,−5, 4], then successive subsequence [4,−1,2,1] has the largest and 6.
Method One: Violence
Loop traversal, output all, judge the maximum and
1#include"iostream"2 #defineMAX 10013 using namespacestd;4 5 intMain () {6 intN, A[max], sum, maxsum;7 8CIN >>N;9 for(inti =0; i<n; i++)Ten { OneCIN >>A[i]; A } -Maxsum = a[0]; - the for(inti =0; i<n; i++) - { -sum =0; - for(intj = i; j<n; J + +) + { -Sum + =A[j]; + if(maxsum<sum) AMaxsum =sum; at } - } -cout <<maxsum; - -}
It is important to note that the array may be all minus { -1,-2,-3,-4}, with a maximum of-1.
Time complexity O (n^2)
Method Two:
Iterate through the array, then determine the value of each element in the array to compare it to 0, if it is greater than or equal to 0, and then determine whether the sum of the previous subarray is greater than 0, if the previous sub-array and less than 0, then the current element is the sum of the current sub-array. If the sum of the previous subarray is greater than 0, the sum of the current element and the sum of the previous subarray is added, and the sum of the sums is the sum of the current sub-array. If it is less than 0, determine if Max is greater than or equal to 0 if Max is greater than or equal to 0 adds the current element to the sum of the previous subarray, sums it up as the sum of the current sub-array, skips the loop if Max is less than 0 The sum of the current subarray compares the sum of the current sub-array with the Max Max for the current element if it is greater than the maximum value, the update
1#include <iostream>2 3 using namespacestd;4 5 intMain ()6 {7 intN, s[Ten], sum, Max;8 9CIN >>N;Ten for(inti =0; I < n; ++i) OneCIN >>S[i]; A - for(inti =0; I < n; ++i) - { the if(i = =0) -Max = SUM = S[i];//initializes sum and Max to the value of the first element in the array. - Else - { + if(S[i] >=0) - { + if(Sum <=0) Asum =S[i]; at Else -sum = sum +S[i]; - } - Else - { - if(Max >=0) in { -sum =0; to Continue; + } - the Else *sum =S[i]; $ }Panax Notoginseng - if(Sum >Max) theMax =sum; + } A } thecout <<"max ="<< Max <<Endl; + return 0; -}
The time complexity is O (n).
The beauty of programming 2.14 to find the maximum of the sum of the array's sub-arrays