最大子序列求和

Question:

Given intergers A1,A2,…,An,find the maximum Subsequence Sum Problem


Solution:

有很多方法可以解决这个问题。下面我只给出我认为最好的算法。

 1 //linear-time maximum contiguous subsequence sum algorithm
 2 
 3 int maxSubSum(const vector< int> & a)
 4 {
 5     int maxSum=a[0],thisSum=0;
 6 
 7     for(int j=0;j<a.size();++j)
 8     {   
 9         thisSum+=a[j];
10         if (thisSum>maxSum)
11             maxSum=thisSum;
12         else if (thisSum< 0)
13             thisSum= 0;
14     }   
15 
16     return maxSum;
17 }

 


Analysis:

算法复杂度为O(N),程序简单易懂


Author: Cat

posted @ 2014-04-16 09:10  猫了个妖喵  阅读(132)  评论(0编辑  收藏  举报