扫描算法求解连续子向量的最大和问题(Python)

上篇用有限状态机来求解,其实也是进行了一遍扫描,只是我把问题考虑的复杂了。

对于扫描,我觉得首先要问自己3个问题:

1. 如何扫描 (这里是遍历数组元素)

2. 每次扫描会改变什么 (这里的算法会改变maxendinghere,前一篇的算法是改变状态)

3. 改变的东西会对结果有影响么 (maxendinghere如果大于maxsofar,那么maxsofar就被赋值为maxendinghere)

不同的考虑问题的方式引入不同的解决方案,其中的差距太大了!!前一篇我太关注正负号了,导致我采用了序列分段,状态转移的方式去解决问题;这里的解法关注最大和,以及有可能影响最大和的因素,maxsofar和maxendinghere的相对大小。虽然时间复杂度都是O(n),但是,高下立现!

代码如下(python):

 

#!/usr/bin/python                                                                                                                                                      

def scan(vector):               # return (maxsofar, low, high)                                                                                                         
    length = len(vector)
    maxsofar = 0
    maxendinghere = 0
    low = 0
    high = 0
    low2 = 0
    high2 = 0
    for i in range(0, length):
        if maxendinghere + vector[i] > 0:
            maxendinghere = maxendinghere + vector[i]
            high2 = i+1
        else:
            maxendinghere = 0
            low2 = i+1
        if maxsofar >= maxendinghere:
            high = high
            low = low
            maxsofar = maxsofar
        else:
            high = high2
            low = low2
            maxsofar = maxendinghere
    return (maxsofar, low, high)

def test():
    vector = [-1, -1, -1, -1]
    (maxsofar, low, high) = scan(vector)
    print vector
    print maxsofar, low, high
    print

    vector = [1, -1, -1, -1]
    (maxsofar, low, high) = scan(vector)
    print vector
    print maxsofar, low, high
    print

    vector = [-1, -1, -1, 1]
    (maxsofar, low, high) = scan(vector)
    print vector
    print maxsofar, low, high
    print

    vector = [-1, 2, 3, -4]
    (maxsofar, low, high) = scan(vector)
    print vector
    print maxsofar, low, high
    print

    vector = [1, 2, 3, 4]
    (maxsofar, low, high) = scan(vector)
    print vector
    print maxsofar, low, high
    print

    vector = [31, -41, 59, 26, -53, 58, 97, -93, -23, 84]
    (maxsofar, low, high) = scan(vector)
    print vector
    print maxsofar, low, high
    print

def main():
    test()

if __name__ == '__main__':
    main()

运行结果:

root@localhost :/home/James/mypro/Python# ./scan.py
[-1, -1, -1, -1]
0 0 0

[1, -1, -1, -1]
1 0 1

[-1, -1, -1, 1]
1 3 4

[-1, 2, 3, -4]
5 1 3

[1, 2, 3, 4]
10 0 4

[31, -41, 59, 26, -53, 58, 97, -93, -23, 84]
187 2 7

root@localhost :/home/James/mypro/Python#

 

后记:感觉python真的很适合写这种小demo,又快又方便。

转载于:https://my.oschina.net/u/158589/blog/61172

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值