求最大子列和

栏目: 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--


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Traction: A Startup Guide to Getting Customers

Traction: A Startup Guide to Getting Customers

Gabriel Weinberg、Justin Mares / S-curves Publishing / 2014-8-25 / USD 14.99

Most startups end in failure. Almost every failed startup has a product. What failed startups don't have is traction -- real customer growth. This book introduces startup founders and employees to......一起来看看 《Traction: A Startup Guide to Getting Customers》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具