Maximum Value and extension of the sum of child arrays in the beauty of programming (can be connected at the beginning and end)
Case 1: the start and end connections are not allowed.
This situation is very common. The method is dynamic planning, and method 3 of the beauty of programming provides an understanding method. The code is provided here.
Int maxSubSum (vector
& Data) {int length = data. size (); assert (length> = 0); int maxSum = data [length-1], startSum = data [length-1], begin = length-1, I; for (I = length-2; I> = 0; I --) {startSum = max (data [I], data [I] + startSum ); // if (startSum> maxSum) {begin = I; maxSum = startSum; // sum of the current largest sub-array} startSum = 0; for (; begin <length & startSum! = MaxSum; startSum + = data [begin], begin ++) cout <data [begin] <""; cout <endl; return maxSum ;}
Scenario 2: Arrays can be connected at the beginning and end
There are two solutions to the problem:
1) The solution does not go through A [n-1] to A [0], that is, the normal request for the maximum value of the subarray and
2) The solution spans A [n-1] to A [0]
In 2nd cases, there are two possibilities (2.1) that contain the entire array; (2.2) that contains two parts, one starting from A [0] and the other ending with A [n-1, this is equivalent to deleting one or the smallest sub-array from array A. When the minimum value is 0, that is, all is not 0, it is the same as (2.1. I personally think that the case where the solution is from A [n-1] to A [0] must be greater than the case where the solution is not crossed. Therefore, the final result is the subarray of the sum of all elements minus the negative number of the absolute value. The Code is as follows:
Int maxSubSumEndToEnd (vector
& Data) {int length = data. size (); assert (length> = 0); int minSum = data [length-1], startSum = data [length-1], allSum = data [length-1], begin = length-1, I, j; for (I = length-2; I> = 0; I --) {allSum + = data [I]; startSum = min (data [I], data [I] + startSum); if (startSum <minSum) {begin = I; minSum = startSum; // calculate the negative subarray with the maximum absolute value} if (minSum> 0) {minSum = 0; begin = 0;} startSum = 0; j = begin; (; j <length & startSum! = MinSum; startSum + = data [j], j = (j + 1) % length); // locate the start position jfor (I = j; I! = Begin; I = (I + 1) % length) cout <data [I] <""; cout <endl; return (allSum-minSum );}
If you have any questions, please correct them. Thank you.