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; 10 for( int i = 0; i < a.length; i++ ) 11 for( int j = i; j < a.length; j++ ) { 13 int thisSum = 0; 14 for( int k = i; k <= j; k++ ) 15 thisSum += a[ k ]; 16 17 if( thisSum > maxSum ) { 19 maxSum = thisSum; 20 seqStart = i; 21 seqEnd = j; 22 } 23 } 25 return maxSum; 26 } figure 5.4 A cubic maximum contiguous subsequence sum algorithm.
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 10 for( int i = 0; i < a.length; i++ ) { 12 int thisSum = 0; 13 for( int j = i; j < a.length; j++ ) { 15 thisSum += a[ j ]; 16 17 if( thisSum > maxSum ) { 19 maxSum = thisSum; 20 seqStart = i; 21 seqEnd = j; 22 } 23 } 24 } 25 26 return maxSum; 27 } figure 5.5 A quadratic maximum contiguous subsequence sum algorithm.
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++ ) { 13 thisSum += a[ j ]; 14 15 if( thisSum > maxSum ) 16 { 17 maxSum = thisSum; 18 seqStart = i; 19 seqEnd = j; 20 } 21 else if( thisSum < 0 ) 22 { 23 i = j + 1; 24 thisSum = 0; 25 } 26 } 27 return maxSum; 28 } figure 5.8 A linear maximum contiguous subsequence sum algorithm.
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; 10 int thisSum = 0; 11 12 for( int j = 0; j < a.length; j++ ) { 13 thisSum = max( 0, thisSum + a[ j ] ); 14 maxSum = max( maxSum, thisSum ); 15 } 16 return maxSum; 17 } En förenklad version av den linjära algoritmen.