(1)the obvious O(N^3) algorithm
/** */
/**
cibic maximum contiguous subsequence sum algorithm.
seqStart and seqEnd represent the actual best sequence
*/
public static int maxSubsequenceSum(int [] a)
... {
int maxSum =0;
cibic maximum contiguous subsequence sum algorithm.
seqStart and seqEnd represent the actual best sequence
*/
public static int maxSubsequenceSum(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;
}
return maxSum;
}
an improved O(N^2) algorithm
在O(N^3)基础上改进:除去了最内的循环原因在于重复的计算thisSum是不必要的
/**/
/*
Quadratic maximum contigous subsequence sum algorithm
seqStart and seqEnd represent the actual best sequence
*/
public static int maxSubsequenceSum (int [] a)
... {
int maxSum = 0;
for (int i=0;i<a.length;i++)
...{
int thisSum=0;
for (int j=i+1; j<a.length ; j++)
...{
thisSum +=a[j];
if(thisSum >maxSum)
...{
maxSum=thisSum;
seqStart = i;
seqEnd =j;
}
}
}
return maxSum;
}
Quadratic maximum contigous subsequence sum algorithm
seqStart and seqEnd represent the actual best sequence
*/
public static int maxSubsequenceSum (int [] a)
... {
int maxSum = 0;
for (int i=0;i<a.length;i++)
...{
int thisSum=0;
for (int j=i+1; j<a.length ; j++)
...{
thisSum +=a[j];
if(thisSum >maxSum)
...{
maxSum=thisSum;
seqStart = i;
seqEnd =j;
}
}
}
return maxSum;
}
a linear algorithm
Theorem : any i, let Ai..j be the first sequence ,with Si..j<0. Then ,for any i<=p<=j and
p<=q,Ap..q either is not a maximum contiguous subsequence or is equal to an
already seen maximum contiguous subsequence
证明略。
/**/
/*
linear maximum contigous subsequence sum algorithm
seqStart and seqEnd represent the actual best sequence
*/
public static int maxSubsequenceSum ( int [] a)
... {
int maxSum = 0;
int thisSum =0;
for (int i=0,j=0;j<a.length;j++)
...{
thisSum+=a[i];
if(thisSum >maxSum)
...{
maxSum=thisSum;
seqStart = i;
seqEnd =j;
}else if(thisSum<0)...{
i=j+1;
thisSum=0;
}
}
return maxSum;
}
linear maximum contigous subsequence sum algorithm
seqStart and seqEnd represent the actual best sequence
*/
public static int maxSubsequenceSum ( int [] a)
... {
int maxSum = 0;
int thisSum =0;
for (int i=0,j=0;j<a.length;j++)
...{
thisSum+=a[i];
if(thisSum >maxSum)
...{
maxSum=thisSum;
seqStart = i;
seqEnd =j;
}else if(thisSum<0)...{
i=j+1;
thisSum=0;
}
}
return maxSum;
}