最大连续子序列和

下面介绍一个线性的算法,这个算法是许多聪明算法的典型:运行时间是明显的,但是正确性则很不明显(不容易理解)。

//线性的算法O(N) 

long maxSubSum4(const vector<int>& a) 

       long maxSum = 0, thisSum = 0; 

       for (int j = 0; j < a.size(); j++) 

       

              thisSum += a[j]; 

              if (thisSum > maxSum) 

                     maxSum = thisSum; 

              else if (thisSum < 0) 

                     thisSum = 0; 

       

       return maxSum; 

}

posted @ 2017-09-08 22:04  漫游的鱼  阅读(132)  评论(0)    收藏  举报