求序列的最大连续加权值

分治法 时间花费NlogN
 

int max3(int maxLeftSum, int maxRightSum, int maxMerge){return maxLeftSum > maxRightSum ? (maxLeftSum > maxMerge ? maxLeftSum : maxMerge) : (maxRightSum > maxMerge ? maxRightSum : maxMerge);}int maxSumRec(const vector &a, int left, int right){if (left == right) // Base caseif (a[left] > 0)return a[left];elsereturn 0;int center = (left + right) / 2;int maxLeftSum = maxSumRec(a, left, center);int maxRightSum = maxSumRec(a, center + 1, right);int maxLeftBorderSum = 0, leftBorderSum = 0;for (int i = center; i >= left; i--){leftBorderSum += a[i];if (leftBorderSum > maxLeftBorderSum)maxLeftBorderSum = leftBorderSum;}int 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);}int maxSubSum3(const vector &a){return maxSumRec(a, 0, a.size() - 1);}int _tmain(int argc, _TCHAR* argv[]){vector MySubsequence = { 34, -61, 87, 39, 72, 3, -3, 5, 8, 4, 22, -12, 34, 85, 43, 23, 67, 34, 67, 28, -59, 77, 35, 74, 84, 48, 44, 59, 53, 66 };cout<<maxSubSum3(MySubsequence)<<endl;return 0;}

线性扫描 时间花费O(N)

/*线性*/int maxSubSum4(const vector &a){int MaxSub = 0; int thisSub = 0;for (int i = 0; i < a.size(); i++){thisSub += a[i];if (thisSub > MaxSub)MaxSub = thisSub;else if (thisSub < 0)thisSub = 0;}return MaxSub;}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值