The maxinum contiguous subsequence sum problem

(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;
}

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;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值