有3種常見的演算法實現該要求,下面將按效率由低到高依次實現:
#-*- coding:gb2312 -*-</p><p>def f1(arg):<br /> """ 求最大序列值演算法1,效率O(N3)<br /> """<br /> if not isinstance(arg, type([])):<br /> return -1<br /> max = sum = 0<br /> for e in arg:<br /> for i in arg[arg.index(e):]:<br /> sum = 0<br /> for j in arg[arg.index(e):arg.index(i)+1]:<br /> sum += j<br /> if max < sum:<br /> max = sum<br /> return max</p><p>def f2(arg):<br /> """ 求最大序列值演算法2,效率O(N2)<br /> """<br /> if not isinstance(arg, type([])):<br /> return -1<br /> max = 0<br /> for e in arg:<br /> sum = 0<br /> for i in arg[arg.index(e):]:<br /> sum += i<br /> if max < sum:<br /> max = sum<br /> return max</p><p>def f3(arg):<br /> """ 求最大序列值演算法3,效率O(N)<br /> """<br /> if not isinstance(arg, type([])):<br /> return -1<br /> max = sum = 0<br /> for e in arg:<br /> sum += e<br /> if max < sum:<br /> max = sum<br /> elif sum < 0:<br /> sum = 0<br /> return max</p><p>if __name__ == "__main__":<br /> print(f1([1,2,3,4,5,6,7]))<br /> print(f2([1,-2,3,4,-5,-6,7]))<br /> print(f3([1,2,-3,4,5,-6,7]))</p><p>
三種方法時間花費依次是O(N3),O(N2),O(N)。
並且程式只判斷了輸入參數是否是list類型,並沒有驗證list中的元素的類型,是個漏洞。