Given your sequence
{ -10, 11, 10, -10, 2, 3, -6, 1 }
Then the maximum sum subsequence is technically 27:
sum of { 11, 10, 2, 3, 1 }
If you are looking for a
contiguous subsequence, then the maximum is 21.
As for the code, I'm not too impressed. A lot of times code gets into books that hasn't been either reviewed, or, shockingly, even
compiled.
Whoever wrote this piece wasn't thinking very clearly. It tries to do a couple things the wrong way.
For the problem at hand, finding the maximum continuous subsequence sum, the answer is straightforward, requiring no recursion or 'divide and conquer' style partitioning.
Just discount negative numbers, and find the largest sum of the remaining sequences. If only negative numbers are present, take the largest one (the one with the least magnitude).
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
|
int max_sum( int* arr, int n )
{
// The initial max number will be the first available number, if any.
// (Because no maximum can be less than any single value in the array.)
int max = 0;
if ((arr) && (n)) max = arr[0];
// Our loop is a special nested loop.
// Outer loop: while there are elements still in the array...
int i = 0;
while (i < n)
{
// First inner loop: find the largest individual value in
// a contiguous sequence of negative values.
for (; (i < n) && (arr[i] < 0); ++i)
{
if (arr[i] > max) max = arr[i];
}
// Second inner loop: sum a contiguous sequence of
// positive values.
if ((i < n) && (arr[i] >= 0))
{
int sum = 0;
for (; (i < n) && (arr[i] >= 0); ++i)
{
sum += arr[i];
}
// (Is the sum the new max?)
if (sum > max) max = sum;
}
}
return max;
}
|
Notice how we must be careful to not overrun the array's bounds at every step. (Because the special two-inner-loop nature of the problem -- it is possible that the first inner loop exhausted the elements in the array, so the second inner loop cannot be allowed to try without testing that there are elements to play with.)
Here's a main to test it out.
1 2 3 4 5 6
|
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
int main()
{
vector <int> sequence;
cout << "Enter subsequence: ";
{
string s;
getline( cin, s );
istringstream ss( s );
int n;
while (ss >> n)
{
sequence.push_back( n );
ss.get();
}
}
cout << "max sum = " << max_sum( sequence.data(), sequence.size() ) << "\n";
}
|
Enter subsequence: -10, 11, 10, -10, 2, 3, -6, 1
max sum = 21 |
Enter subsequence: -10 -9 -6 -100
max sum = -6 |
Enter subsequence: -1 2 3 -4 -5 -6 7 -8 -9
max sum = 7 |
Hope this helps.