python 最大子序列之和

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)     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值