码迷,mamicode.com
首页 > 其他好文 > 详细

最大子序列求和模版

时间:2016-07-10 11:13:26      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
long max3(long a, long b, long c) 
{ 
       if (a < b) 
            a = b;
       if (a > c)
              return a;
       else
              return c;
}
long maxSumRec(const vector<int>& a, int left, int right) 
{ 
       if (left == right) 
       { 
              if (a[left] > 0) 
                     return a[left]; 
              else 
                     return 0; 
       }
       int center = (left + right) / 2; 
       long maxLeftSum = maxSumRec(a, left, center); 
       long maxRightSum = maxSumRec(a, center+1, right); 
       //求出以左边对后一个数字结尾的序列最大值 
       long maxLeftBorderSum = 0, leftBorderSum = 0; 
       for (int i = center; i >= left; i--) 
       { 
              leftBorderSum += a[i]; 
              if (leftBorderSum > maxLeftBorderSum) 
                     maxLeftBorderSum = leftBorderSum; 
       } 
       //求出以右边对后一个数字结尾的序列最大值 
       long maxRightBorderSum = 0, rightBorderSum = 0; 
       for (int j = center+1; j <= right; j++) 
       { 
              rightBorderSum += a[j]; 
              if (rightBorderSum > maxRightBorderSum) 
                     maxRightBorderSum = rightBorderSum; 
       } 
 
       return max3(maxLeftSum, maxRightSum,  
              maxLeftBorderSum + maxRightBorderSum); 
} 
long maxSubSum3(const vector<int>& a) 
{ 
       return maxSumRec(a, 0, a.size()-1); 
}
分治法 O(NlogN)

 

最大子序列求和模版

标签:

原文地址:http://www.cnblogs.com/Noevon/p/5657215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!