An even better solution

 

CS 241: Data Structures
Lecture #2: Two Sample Problems in Analysis

An even better solution
bullet Negative-sum subsequences if the sum of a sub-sequence is negative, it cannot contribute to a good solution

Q: why?

Control bar


















































 

CS 241: Data Structures
Lecture #2: Two Sample Problems in Analysis

An even better solution
bullet Negative-sum subsequences
bullet Exploiting negative sums once we see a negative sum, we can skip the i counter forward, past the end of this subsequence

Control bar


















































 

CS 241: Data Structures
Lecture #2: Two Sample Problems in Analysis

An even better solution
bullet Negative-sum subsequences
bullet Exploiting negative sums
bullet A single loop we can use a single loop by starting i out at 0 and updating it (moving it forward) only when necessary

Q: can we skip i forward "too far"? What information must we keep track of?

Control bar


















































 

CS 241: Data Structures
Lecture #2: Two Sample Problems in Analysis

An even better solution
bullet Negative-sum subsequences
bullet Exploiting negative sums
bullet A single loop
bullet Best algorithm (linear)
/**
 * Linear-time maximum contiguous subsequence sum algorithm.
 * seqStart and seqEnd represent the actual best sequence.
 */

public static int maxSubSum3( int [ ] a )
{
    int maxSum = 0;
    int thisSum = 0;

    for( int i = 0, j = 0; j < a.length; j++ )
    {
        thisSum += a[ j ];

        if( thisSum > maxSum )
        {
            maxSum = thisSum;
            seqStart = i;
            seqEnd   = j;
        }
        else if( thisSum < 0 )
        {
            i = j + 1;
            thisSum = 0;
        }
    }

    return maxSum;
}

Control bar