寻找最大子串(线性方法)

来源:互联网 发布:程序员自由职业平台 编辑:程序博客网 时间:2024/05/01 22:40

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)



原创粉丝点击