求两个子数组最大和

题目

在一个数组中找两个子数组,求其最大和(子数组不重合,可以为空)

 

解法

从右向左遍历,找到右边子数组的最大和

再从左向右遍历,找到左边子数组的最大和的同时,找这两者的最大和

两遍 dp 即可

 

代码 

def maxTwoSubStringSum(nums):
    ans = -float('inf')
    leftAns = []
    cur = 0
    
    # from right to left
    for i in range(len(nums)-1, -1, -1):
        if cur < 0:
            cur = nums[i]
        else:
            cur += nums[i]
        ans = max(cur, ans)
        leftAns.append(ans)
    
    leftAns = leftAns[::-1]
    ans = -float('inf')
    rightAns = -float('inf')
    cur = 0

    # from left to right
    for i in range(len(nums)):
        ans = max(ans, rightAns + leftAns[i])
        if cur < 0:
            cur = nums[i]
        else:
            cur += nums[i]
        rightAns = max(cur, rightAns)
        
    
    ans = max(ans, max(leftAns), rightAns)
    return ans


nums = [-1,2,3,4,1,1,5,0]
print(maxTwoSubStringSum(nums))

nums = [-1,2,3,4,1,-100,5,0]
print(maxTwoSubStringSum(nums))

nums = [-1,1]
print(maxTwoSubStringSum(nums))

 

输出:

 

 

 

 

 
posted @ 2022-04-18 19:08  sbj123456789  阅读(100)  评论(0编辑  收藏  举报