首页 > 代码库 > Maxmum subsequence sum problem
Maxmum subsequence sum problem
We have a lot of ways to solve the maximum subsequence sum problem, but different ways take different time.
1、Brute-force algorithm
int maxSubSum1(const vector<int> &a) { int maxSum=0; for(int i=0;i<a.size();i++) for(int j=i;j<a.size();j++) { int sum=0; for(int k=i;k<=j;k++) sum+=a[k]; if(sum>maxSum) maxSum=sum; } return maxSum; } /*The running time is O(n^3) It takes too much time. */
2、a little imporvement
int maxSubSum2(const vector<int>& a ) { int maxSum=0; for(int i=0;i<a.size();i++) { int sum=0; for(int j=i;j<a.size();j++) { sum+=a[j]; if(maxSum<sum) { maxSum=sum; } } } return maxSum; }
3. Divide-conquer algorithm
We can divide this problem into three parts:
(1) First half;
(2) cross the middle parts;
(3) second part;
What we need to do is to find the max sum of the three part.
int max3(int a, int b, int c) { if(a>b) { if(a>c)return a; else return c; } else { if(c>b)return c; else return b; } } int maxSubSum3(cosnt 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; int maxLeftSum=maxSumRec(a, left, center); int maxRightSum=maxSumRec(a, center+1, right); int maxLeftBoderSum=0, leftBoderSum=0; for(int i=center;i>=left;i--) { leftBoderSum+=a[i]; if(leftBoderSum>maxLeftBoderSum) maxLeftBoderSum=leftBoderSum; } int maxRightBoderSum=0, leftBoderSum=0; for(int i=center+1;i<=right;i++) { rightBoderSum+=a[i]; if(rightBoderSum>maxRightBoderSum) maxRightBoderSum=rightBoderSum; } return max3(maxLeftSum, maxLeftBoderSum+maxRightBoderSum,maxRightSum); }
4. The best algorithm
If the start is negative, the sum of the subsequence can not be the max. Hence, any negative subsequence cannot possibly be a prefix of the optimal subsequence.
int maxSubSum4(const vector<int> & a) { int maxSum=0, sum=0; for(int i=0;i<a.size();i++) { sum+=a[i]; if(sum>maxSum) maxSum=sum; else if(sum<0) sum=0; } return maxSum; }
Maxmum subsequence sum problem
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。