(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; 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;
}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;
}
本文介绍了三种不同复杂度的最大连续子序列和算法:O(N^3)、O(N^2)及线性时间复杂度O(N)算法。通过逐步改进,从三次方时间复杂度的穷举法到高效的线性算法,详细展示了算法的设计思路与实现过程。
380

被折叠的 条评论
为什么被折叠?



