Below is a sample code in C++ written using recursion to solve the maximum subsequence problem - not exactly the subsequence, but the sum of the maximum subsequence.
int maxSumRec( const vector<int> & a, int left, int right )
{
if( left == right ) // Base case
if( a[ left]>0)
return a[ left ];
else
return 0;
int center = ( left + right ) / 2;
int maxLeftSum = maxSumRec( a, left, center );
int maxRightSum = maxSumRec( 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 j = center + 1; j <= right; ++j )
{
rightBorderSum += a[ j ];
if( rightBorderSum > maxRightBorderSum )
maxRightBorderSum = rightBorderSum;
}
return max3( maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum );
}
Why does the base case have to return 0 if the single element left is negative? Will it not affect the sum if we return a higher value of 0 instead of the actual negative value? I searched the internet for the explanation of the base case and the problem statement but couldn't find out the explanation.
The empty sequence {}
is a subsequence of {x}
, and its sum is 0. The sum of the sequence {x}
is x, which is obviously less than 0 if x is negative.