A naive solution

 

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

A naive solution
bullet Compute (and store) sum for each subsequence we can use an n x n array sum to store the values for the sums of all possible subsequences from A[i] to A[j], putting the value in the cell sum[i,j]

Q: what part of the array will we fill in?

Control bar


















































 

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

A naive solution
bullet Compute (and store) sum for each subsequence
bullet Finding the result to return the correct answer, we need only fill in the array,then search it for the maximum value

Q: what is the asymptotic running time for this approach (in O notation)?

Control bar


















































 

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

A naive solution
bullet Compute (and store) sum for each subsequence
bullet Finding the result
bullet Keeping a running maximum we can eliminate the search by keeping and updating a "current maximum value" as we fill in the array

Q: does eliminating this (inefficient) search help our asymptotic running time?

Control bar


















































 

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

A naive solution
bullet Compute (and store) sum for each subsequence
bullet Finding the result
bullet Keeping a running maximum
bullet Cutting down on space once we use a running maximum, we need not actually build the array

Q: does eliminating the array of maxima help our asymptotic space usage?

Q: what other "running values" do we need to keep track of?

Control bar


















































 

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

A naive solution
bullet Compute (and store) sum for each subsequence
bullet Finding the result
bullet Keeping a running maximum
bullet Cutting down on space
bullet Code for the naive algorithm (cubic)
/**
 * Cubic maximum contiguous subsequence sum algorithm.
 * seqStart and seqEnd represent the actual best sequence.
 */
 
public static int maxSubSum1( int [ ] a )
{
    int maxSum = 0;

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

            for( int k = i; k <= j; k++ )
                thisSum += a[ k ];

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

    return maxSum;
}

Control bar