【Question]:
Enter an integer array, and the array contains positive and negative numbers. One or more consecutive integers in the array form a sub-array. Each sub-array has a sum. Calculate the maximum sum of all sub-arrays. the time complexity is O (n ).
For example, the input array is 1,-2, 3, 10,-4, 7, 2,-5, and the maximum sub-array is 3, 10,-4, 7, 2, so the output is the sum of 18 of the Child array.
【Dynamic Planning]:
C ++ Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
|
/* See Http://www.cppblog.com/jake1036/archive/2013/04/10/144726.html Http://en.wikipedia.org/wiki/Maximum_subarray_problem F (I): max subsequence value ending at I F (I) = max (f (I-1) + a [I], a [I]) Max f (I) (I = 0,... N-1)
N = 8 -4, 3, 12,-7, 20,-1,-14, 4
3, 12,-7, 20 ---> 28 */
Int dp_forward () { // Time o (n) // Base case F [0] = a [0]; Int maxi = f [0]; For (int I = 1; I <N; I ++) { F [I] = max (f [I-1] + a [I], a [I]); If (maxi <f [I]) { Maxi = f [I]; } } Return maxi; }
Int dp_forward2 () { // Base case Int f = a [0]; Int maxi = a [0]; For (int I = 1; I <N; I ++) { // F = max (f + a [I], a [I]); If (f <0) { F = a [I]; } Else { F + = a [I]; }
If (maxi <f) { Maxi = f; } } Return maxi; } |
【Reference]:
Http://zhedahht.blog.163.com/blog/static/254111742007219147591/
Http://blog.csdn.net/v_JULY_v/article/details/6444021