1.重复利用已经计算的子数组和:O(n2)
def maxSubArr(arr):
if arr == None:
print('数组为空')
return
maxsum = -2**31
i = 0
lens = len(arr)
while i<lens :
j = i
sums = 0
while j<lens :
sums += arr[j]
if sums > maxsum :
maxsum = sums
j += 1
i += 1
return maxsum
2.动态规划法:O(n)
def maxSubArr(arr):
lens = len(arr)
if arr == None or lens<1 :
print('参数不合法')
return
ends = alls = arr[0]
i = 1
while i<lens :
ends = max(ends+arr[i], arr[i]) #包含最后一个元素的最大子数组和
alls = max(ends, alls) #最大子数组和
i += 1
return alls
来源:https://blog.csdn.net/weixin_42712658/article/details/99698085