import java
public final class MaxSumTest
{
static private int seqStart =
static private int seqEnd =
/**
* Cubic maximum contiguous subsequence sum algorithm
* seqStart and seqEnd represent the actual best sequence
*/
public static int maxSubSum
{
int maxSum =
for( int i =
for( int j = i; j < a
{
int thisSum =
for( int k = i; k <= j; k++ )
thisSum += a[ k ];
if( thisSum > maxSum )
{
maxSum = thisSum;
seqStart = i;
seqEnd = j;
}
}
return maxSum;
}
/**
* Quadratic maximum contiguous subsequence sum algorithm
* seqStart and seqEnd represent the actual best sequence
*/
public static int maxSubSum
{
int maxSum =
for( int i =
{
int thisSum =
for( int j = i; j < a
{
thisSum += a[ j ];
if( thisSum > maxSum )
{
maxSum = thisSum;
seqStart = i;
seqEnd = j;
}
}
}
return maxSum;
}
/**
* Linear
* seqStart and seqEnd represent the actual best sequence
*/
public static int maxSubSum
{
int maxSum =
int thisSum =
for( int i =
{
thisSum += a[ j ];
if( thisSum > maxSum )
{
maxSum = thisSum;
seqStart = i;
seqEnd = j;
}
else if( thisSum <
{
i = j +
thisSum =
}
}
return maxSum;
}
/**
* Recursive maximum contiguous subsequence sum algorithm
* Finds maximum sum in subarray spanning a[left
* Does not attempt to maintain actual best sequence
*/
private static int maxSumRec( int [ ] a
{
int maxLeftBorderSum =
int leftBorderSum =
int center = ( left + right ) /
if( left == right ) // Base case
return a[ left ] >
int maxLeftSum = maxSumRec( a
int maxRightSum = maxSumRec( a
for( int i = center; i >= left; i– )
{
leftBorderSum += a[ i ];
if( leftBorderSum > maxLeftBorderSum )
maxLeftBorderSum = leftBorderSum;
}
for( int i = center +
{
rightBorderSum += a[ i ];
if( rightBorderSum > maxRightBorderSum )
maxRightBorderSum = rightBorderSum;
}
return max
maxLeftBorderSum + maxRightBorderSum );
}
/**
* Return maximum of three integers
*/
private static int max
{
return a > b ? a > c ? a : c : b > c ? b : c;
}
/**
* Driver for divide
* subsequence sum algorithm
*/
public static int maxSubSum
{
return a
}
public static void getTimingInfo( int n
{
int [] test = new int[ n ];
long startTime = System
long totalTime =
int i;
for( i =
{
for( int j =
test[ j ] = rand
switch( alg )
{
case
maxSubSum
break;
case
maxSubSum
break;
case
maxSubSum
break;
case
maxSubSum
break;
}
totalTime = System
}
System
+
+
}
private static Random rand = new Random( );
/**
* Simple test program
*/
public static void main( String [ ] args )
{
int a[ ] = {
int maxSum;
maxSum = maxSubSum
System
+
maxSum = maxSubSum
System
+
maxSum = maxSubSum
System
+
maxSum = maxSubSum
System
// Get some timing info
for( int n =
for( int alg =
{
if( alg ==
continue;
getTimingInfo( n
}
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27079.html