A better solution

 

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

A better solution
bullet A code-based view of the problem the cubic running time for the algorithm results from having three nested loops; if we can eliminate one loop, we can bring the time down to quadratic

Control bar


















































 

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

A better solution
bullet A code-based view of the problem
bullet An intuitive view more intuitively, we can just notice that we are needlessly re-computing the values of some subsequences (i.e., those for which we then compute an "extended sum" given one new element)

Control bar


















































 

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

A better solution
bullet A code-based view of the problem
bullet An intuitive view
bullet Cutting out the repetition rather than compute a separate sum for each new value of j (given a fixed i), we can just update the sum by adding in A[j]

Q: what is our new asymptotic running time?

Control bar


















































 

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

A better solution
bullet A code-based view of the problem
bullet An intuitive view
bullet Cutting out the repetition
bullet Code for the quadratic algorithm
/**
 * Quadratic maximum contiguous subsequence sum algorithm.
 * seqStart and seqEnd represent the actual best sequence.
 */
 
public static int maxSubSum2( int [ ] a )
{
    int maxSum = 0;

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

            if( thisSum > maxSum )
            {
                maxSum = thisSum;
                seqStart = i;
                seqEnd   = j;
            }
        }
    }

    return maxSum;
}

Control bar