掃描算法求解連續子向量的最大和問題(Python)

上篇用有限狀態機來求解,其實也是進行了一遍掃描,只是我把問題考慮的複雜了。python

對於掃描,我以爲首先要問本身3個問題:算法

1. 如何掃描 (這裏是遍歷數組元素)數組

2. 每次掃描會改變什麼 (這裏的算法會改變maxendinghere,前一篇的算法是改變狀態)spa

3. 改變的東西會對結果有影響麼 (maxendinghere若是大於maxsofar,那麼maxsofar就被賦值爲maxendinghere).net

不一樣的考慮問題的方式引入不一樣的解決方案,其中的差距太大了!!前一篇我太關注正負號了,致使我採用了序列分段,狀態轉移的方式去解決問題;這裏的解法關注最大和,以及有可能影響最大和的因素,maxsofar和maxendinghere的相對大小。雖然時間複雜度都是O(n),可是,高下立現!code

代碼以下(python):get

 

#!/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()

運行結果:class

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

[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,又快又方便。

相關文章
相關標籤/搜索