Lecture02

Lecture02 - CS2134 Max Contiguous Subsequence Problem (redo...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS2134 Max Contiguous Subsequence Problem (redo from Lecture 1) Given sequence A1,...,An of numbers find i and j such that Ai + ... + Aj is maximal. 1, 2, -4, 1, 2, -1, 4, -2, 1 Max subsequence is 1,2,-1,4 whose sum is 6 CS2134 Naive Algorithm 1 2 -4 1 2 -1 4 -2 2 For each pair i, j compute sum of elements from i to j, keeping track of maxsofar. For each pair (i,j): thissum =0; for (k=i; k <=j; k++) thissum += a[k]; ... if (sum > maxsofar) maxsofar = thissum; e.g., when (i,j) = (1,4), sum = 2 - 4 +1 +2 = 1 Triply nested loop: O(n 3 ) CS2134 template <class Comparable> Comparable maxSubsequenceSum1( const vector<Comparable> & a, int & seqStart, int & seqEnd ) { int n = a.size( ); Comparable maxSum = 0; for( int i = 0; i < n; i++ ) for( int j = i; j < n; j++ ) { Comparable thisSum = 0; for( int k = i; k <= j; k++ ) thisSum += a[ k ]; if( thisSum > maxSum ) { maxSum = thisSum; seqStart = i; seqEnd = j; } } return maxSum; } CS2134 Somewhat better Algorithm Sum(i, j+1) = Sum(i,j) + A[j+1] Remember Sum(i,j) instead of recomputing it. Doubly nested for loop: O(n 2 ) CS2134 Comparable maxSubsequenceSum2( const vector<Comparable> & a int & seqStart, int & seqEnd ) { int n = a.size( ); Comparable maxSum = 0; for( int i = 0; i < n; i++ ) { Comparable thisSum = 0; for( int j = i; j < n; j++ ) { thisSum += a[ j ]; if( thisSum > maxSum ) { maxSum = thisSum; seqStart = i; seqEnd = j; } } } return maxSum; } CS2134...
View Full Document

Page1 / 19

Lecture02 - CS2134 Max Contiguous Subsequence Problem (redo...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online