python 最大子序列之和
解法一:暴力求解1 O ( N 3 ) O(N^3) O(N3)
list = [-2,11,-4,13,-5,-2]
def MaxSubsepuenceSum(list):
MaxSum = 0
length = len(list)
for i in range(length):
for j in range(i,length):
thisSum = 0
for k in range(i,j+1):
thisSum += list[k]
if thisSum > MaxSum:
MaxSum = thisSum
return MaxSum
print(MaxSubsepuenceSum(list))
暴力求解2 O ( N 2 ) O(N^2) O(N2)
list = [-2,11,-4,13,-5,-2]
def MaxSubsepuenceSum(list):
MaxSum = 0
length = len(list)
for i in range(length):
thisSum = 0
for j in range(i,length):
thisSum += list[j]
if thisSum > MaxSum:
MaxSum = thisSum
return MaxSum
print(MaxSubsepuenceSum(list))
解法二:分而治之与递归
list = [-2,11,-4,13,-5,-2]
def MaxSubSum(list:list,left:int,right:int):
if left == right:
if list[left]>0:
return list[left]
else:
return 0
center = (left+right)//2
MaxLeftSum = MaxSubSum(list,left,center)
MaxRightSum = MaxSubSum(list,center+1,right)
MaxLeftBorderSum = 0
LeftBorderSum = 0
for i in range(center,left-1,-1):
LeftBorderSum += list[i]
if LeftBorderSum > MaxLeftBorderSum:
MaxLeftBorderSum = LeftBorderSum
MaxRightBorderSum = 0
RightBorderSum = 0
for i in range(center+1,right+1):
RightBorderSum += list[i]
if RightBorderSum > MaxRightBorderSum:
MaxRightBorderSum = RightBorderSum
return max(max(MaxLeftSum,MaxRightSum),MaxLeftBorderSum+MaxRightBorderSum)
answer=MaxSubSum(list,0,5)
print(answer)