Array: int [] args = {-2, 11,-4, 13,-5, 2,-5,-3, 12,-9 };
Maximum Sum: 21
Divide (devide-and-conquer ):
The idea is to divide the problem into two subproblems that are roughly equal, and then solve them recursively. This is the "points" part. In the "governance" phase, the solution of the two subproblems is fixed together, and a small amount of additional work may be done to finally obtain the solution of the entire problem.
The preceding test data is divided into two groups: {-2, 11,-4, 13,-5}; {2,-5,-3, 12,-9 }. The final result may exist: in the left array; In the right array; find
The last element of left (in this example
-5
) In
Left
(In this example
11,-4, 13,-5) and contain
Right Start Element (2
) In
Second
Maximum subsequence (
2,-5,-3, 12) and then add the result.
Below I will paste the C # test code I briefly wrote as follows:
/// <Summary>
/// Grouping Algorithm
/// </Summary>
/// <Param name = "a"> A. </param>
/// <Param name = "left"> The left. </param>
/// <Param name = "right"> The right. </param>
/// <Returns> </returns>
Int getMaxSumUsingDivideConquer (int [] a, int left, int right)
{
If (left = right)
{
If (args [left]> 0)
{
Return args [left];
}
Else
{
Return 0;
}
}
Int center = (left + right)/2;
Int maxleftsum = getmaxsumusingdivideconquer (A, left, center );
Int maxrightsum = getmaxsumusingdivideconquer (A, center + 1, right );
Int maxleftbordersum = 0, leftbordersum = 0;
For (INT I = center; I> = left; I --)
{
Leftbordersum + = A [I];
If (leftbordersum> maxleftbordersum)
{
Maxleftbordersum = leftbordersum;
}
}
Int maxrightbordersum = 0, rightbordersum = 0;
For (INT I = center + 1; I <= right; I ++)
{
RightBorderSum + = a [I];
If (RightBorderSum> maxRightBorderSum)
{
MaxRightBorderSum = RightBorderSum;
}
}
Return GetMaxValueFromTreeNumber (maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum); // determines the maximum number of three functions.
}
/// <Summary>
/// Gets the max value from tree number.
/// </Summary>
/// <Param name = "maxLeftSum"> The max left sum. </param>
/// <Param name = "maxRightSum"> The max right sum. </param>
/// <Param name = "third"> The third. </param>
/// <Returns> </returns>
Private int GetMaxValueFromTreeNumber (int maxLeftSum, int maxRightSum, int third)
{
Int max = 0;
If (max <maxLeftSum)
{
Max = maxLeftSum;
}
If (max <maxRightSum)
{
Max = maxRightSum;
}
If (max <third)
{
Max = third;
}
Return Max;
}
The calling method is as follows:
Int Total = getmaxsumusingdivideconquer (ARGs, 0, argS. Length-1 );
MessageBox. Show ("the value of maxsum is:" + total. tostring ());