尋找最大子串(線性方法)

O(n)

#!/usr/bin/python

'''file name: maxsum.py
   --P75
   --find maximum subarray sum, O(n)
   --author: zevolo, 2012.05.11
'''
def find_max_sum(list):
    now_max = list[0]
    low = high = 0
    
    right_max = 0
    right_low = right_high = -1
    for i in range(1, len(list)):
        if right_low == -1 or right_max <= 0:
            right_low = right_high = i
            right_max = list[i]
        else:
            right_max += list[i] 
            right_high = i
        if right_max > now_max:
            low = right_low
            high = right_high
            now_max = right_max
        #print "now max %d,%d" % (low, high)
    return (low, high, now_max)

if __name__ == '__main__':
    l = [1, -2, 3, 10, -4, 7, 2, -5]
    print l
    (low, high, sum) = find_max_sum(l)
    out = l[low:high+1]
    print (out, sum)



發佈了47 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章