A one-dimensional array with n integer elements (a[0], a[1],... A[n-1]), to find the maximum value of the sum of the subarray.
Example:
[1,-2, 3, 5,-3, 2] returns: 8
[0,-2, 3, 5,-1, 2] returns: 9
[-9,-2,-3,-5,-3] returns: 2
Note that if you consider the array end-to-end connection, then 1, the first to calculate the maximum value max2, from the tail to the head scan, find the maximum M1, and record the maximum position I, and then scan from head to tail, find the maximum value m2, and record the maximum position J, if i>j, then compare m1+m2 with Max, The maximum value, if i<=j, makes m = a[0]+a[1]+a[2]+ ... A[n-1], find the maximum value between M and Max. int MaxSum4 (int *a, int n,int &beg,int &end) { if (a==null| | n<=1) { cout<< "Error Input" < < ' \ n '; exit (0); } if (n==1) return a[0]; int pos = 0; int cursum = A[0]; int maxsum = a[0]; for (int i = 1; I<n;++i) { if (CurSum<=0) cursum = 0; cursum + = A[i]; &nbSp; if (cursum>=maxsum) { maxsum = cursum; pos = i; } } int pos1 = 0,max1 = A[0]; cursum = a[0]; for (int i = 1;i <=n-1;++i) { cursum + = A[i]; if (CURSUM>=MAX1) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;MAX1 = CurSum; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;POS1 = i; } } cursum = A[n-1]; int Pos2 = n-1, max2 = A[n-1]; for (int j = n-2; j>=0;--j) { cursum + = a[j]; if (CURSUM>=MAX2) { Max2 = Cursum; pos2 = j; } } int sum = 0; if (POS1>=POS2) { for (int i = 0; i <n; ++i) sum+=A[i]; } else { for (int i = 0; i<=pos1; ++i) { sum+=a[i]; } for (int j = n-1; j>=pos2;--j) { sum+=A[j]; } } int temp = MaxSum>sum? Maxsum:sum; if (maxsum==temp) { end = Pos; while (temp!=0) { temp-=a [Pos--]; } beg = ++pos; return maxsum; } else&nbsP; { if (POS1>=POS2) { beg = 0; end = n-1; } else { end = pos2; beg = pos1; } return sum; } return maxsum>sum? Maxsum:sum;}
The sum of the largest subarray in the array