1. Title Description
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).
2. Dynamic planning
Set Currsum (i) for the first I element, with the first element as the end, and the largest contiguous subarray of the and. Then you get a recursive formula.
Currsum (i+1) = Currsum (i) + A (i) (currsum >= 0)
A (i) (Currsum < 0)
The above formula is very good understanding, for Currsum (i+1), Equals to Currsum (i) plus a[i], but if currsum (i) < 0, plus a negative number, it will be better than no small, so simply do not add
Then the problem of finding the largest subarray of array A[n] is converted to Max (Currsum (i)) (1<= i <=size)
Based on the above ideas, summed up the following two total implementation
1. Borrowing an auxiliary array in this implementation Currsum[n],currsum[i] represents the largest and most of all sub-arrays ending with the I element
First iterate over the array a[n], get currsum[n], and then find the largest one from all the elements of the array currsum[n] to get the answer.
1 //Author:jincheng 2 //date:170315 3 //description:find max sum of Subarray by DP method 4 //complexity:time o (n) Space o (n) 5 6#include <iostream>7 using namespacestd;8 9Template <typename t>Ten voidPrint (T *a,intsize); One ATemplate <typename t> - voidMaxsumsubarray (T *a,intsize) - { theT *currsum =NewT[size+1]; Auxiliary Arrays -currsum[1] = a[1]; -T maxsum;//maximum value of global - for(inti =2; I <= size;i++) + { - if(currsum[i-1] <0) + { ACurrsum[i] =A[i]; at } - Else - { -Currsum[i] + =A[i]; - } - } inMaxsum = [1]; - for(inti =2; i<=size;i++) to { + if(Maxsum <Currsum[i]) - { theMaxsum =Currsum[i]; * } $ }Panax Notoginsengcout <<"The max sum of Subarray is"<< Maxsum <<Endl; - the Deleteb; + } A the intMain () + { - intA[] = {0,-1,-2,-7,-8,-5}; $Print (A,5); $Maxsumsubarray (A,5); - return 0; - } - WuyiTemplate <typename t> the voidPrint (T *a,intsize) - { Wu for(intI=1; I <= size;i++) - Aboutcout <<"a["<< I <<"] = "<< A[i] <<Endl; $}
The data structure and algorithm