Scenario 1: I don't agree with end-to-end
This is not a common scenario, but it is a dynamic programming approach. The method of programming beauty three gives the solution. This is where the code is given directly.
int maxsubsum (vector<int>& 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);// The sum of the largest sub-arrays beginning with the number of I (Startsum > maxsum) {begin = I;maxsum = startsum;//The current largest subarray and}}startsum = 0;for (; begin < Length &am p;& startsum! = maxsum;startsum+=data[begin],begin++) cout << Data[begin] << ""; cout << Endl; return maxsum;}
scenario Two, array can be connected to end to end
The solution of the problem can be divided into two situations:
1) The solution did not cross a[n-1] to a[0]. That is, the maximum value of the normal subarray and
2) solution across a[n-1] to a[0]
For the 2nd case, there are two possible (2.1) including the entire array; (2.2) includes two parts. A paragraph beginning with a[0] and ending with a[n-1], which is equivalent to removing one and the smallest subarray from array A, and when the minimum and 0 o'clock are all non-0 elements, this is the same as (2.1). And personally feel that the solution across the a[n-1] to a[0] is certainly greater than the situation has not crossed. So. The final result is a negative subarray of all elements and minus the absolute value, with detailed code such as the following:
int Maxsubsumendtoend (vector<int>& 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;//Seek absolute maximum negative number Subarray} }if (Minsum > 0) {minsum = 0;begin = 0;} Startsum = 0;j = Begin;for (; J < length && startsum! = Minsum;startsum+=data[j],j = (j + 1)%length);//Find the place to start JFO R (i = j;i! = Begin;i = (i+1)%length) cout << data[i] << ""; cout << Endl;return (allsum-minsum);}
If you have any questions, please correct me, thank you.
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Programming sub-arrays and maximum and expansive beauty (connected end-to-end)