求最大子列和
栏目: JavaScript · 发布时间: 5年前
内容简介:算法很重要呐 :smile::smile:
var nums = [1, -2, 2, -13, 6, -10, 3, 12] /// O(n^3) func maxSubSequenceSum1() { var maxSum = 0 for i in 0..<nums.count { for j in i..<nums.count { var thisSum = 0 for k in i...j { thisSum += nums[k] } if thisSum > maxSum { maxSum = thisSum } } } print(maxSum) } /// O(n^2) func maxSubSequenceSum2() { var maxSum = 0 for i in 0..<nums.count { var thisSum = 0 for j in i..<nums.count { thisSum += nums[j] if thisSum > maxSum { maxSum = thisSum } } } print(maxSum) } /// O(n) func maxSubSequenceSum3() { var maxSum = 0, thisSum = 0 for i in 0..<nums.count { thisSum += nums[i] if thisSum > 0 { maxSum = thisSum } else { //如果thisSum小于0,则不可能使后面的部分和增大,抛弃. thisSum = 0 } } print(maxSum) } maxSubSequenceSum1() maxSubSequenceSum2() maxSubSequenceSum3()
算法很重要呐 :smile::smile:
--EFO--
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。