Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 // Cubic maximum contiguous subsequence sum algorithm.

Similar presentations


Presentation on theme: "1 // Cubic maximum contiguous subsequence sum algorithm."— Presentation transcript:

1 1 // Cubic maximum contiguous subsequence sum algorithm.
2 // seqStart and seqEnd represent the actual best sequence. 4 public static int maxSubsequenceSum1( int[] a ) { 8 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 ]; 16 if( thisSum > maxSum ) { maxSum = thisSum; seqStart = i; seqEnd = j; } } return maxSum; 26 } figure A cubic maximum contiguous subsequence sum algorithm.

2 1 // Quadratic maximum contiguous subsequence sum algorithm.
2 // seqStart and seqEnd represent the actual best sequence. 4 public static int maxSubsequenceSum2( int[] a ) { 8 int maxSum = 0; 9 for( int i = 0; i < a.length; i++ ) { int thisSum = 0; for( int j = i; j < a.length; j++ ) { thisSum += a[ j ]; 16 if( thisSum > maxSum ) { maxSum = thisSum; seqStart = i; seqEnd = j; } } } 25 return maxSum; 27 } figure A quadratic maximum contiguous subsequence sum algorithm.

3 1 // Linear maximum contiguous subsequence sum algorithm.
2 // seqStart and seqEnd represent the actual best sequence. 4 public static int maxSubsequenceSum3( int[] a ) { 8 int maxSum = 0; 9 int thisSum = 0; 10 11 for( int i = 0, j = 0; j < a.length; j++ ) { thisSum += a[ j ]; 14 if( thisSum > maxSum ) { maxSum = thisSum; seqStart = i; seqEnd = j; } else if( thisSum < 0 ) { i = j + 1; thisSum = 0; } 26 } 27 return maxSum; 28 } figure A linear maximum contiguous subsequence sum algorithm.

4 1 public int max( int x, int y ) { 2 return x > y ? x : y; 3 } 4
6 public static int maxSubsequenceSum3x( int[] a ) { 9 int maxSum = 0; int thisSum = 0; 11 for( int j = 0; j < a.length; j++ ) { thisSum = max( 0, thisSum + a[ j ] ); maxSum = max( maxSum, thisSum ); } return maxSum; 17 } En förenklad version av den linjära algoritmen.


Download ppt "1 // Cubic maximum contiguous subsequence sum algorithm."

Similar presentations


Ads by Google