42. 最大子数组 II
给定一个整数数组,找出两个 不重叠 子数组使得它们的和最大。
每个子数组的数字在数组中的位置应该是连续的。
返回最大的和。
样例
给出数组 [1, 3, -1, 2, -1, 2]
这两个子数组分别为 [1, 3]
和 [2, -1, 2]
或者 [1, 3, -1, 2]
和 [2]
,它们的最大和都是 7
挑战
要求时间复杂度为 O(n)
注意事项
子数组最少包含一个数
class Solution:
"""
@param: nums: A list of integers
@return: An integer denotes the sum of max two non-overlapping subarrays
"""
def maxTwoSubArrays(self, nums):
# write your code here
if len(nums) < 3:
return sum(nums)
n = len(nums)
#倒序排列
strnums = nums[::-1]
leftmax = [nums[0]]
rightmax = [strnums[0]]
newleftmax = nums[0]
newrightmax = strnums[0]
for i in range(1, n):
#对从左到右正序数字进行加和判断
if newleftmax > 0:
newleftmax += nums[i]
else:
newleftmax = nums[i]
leftmax.append(max(newleftmax, leftmax[-1]))
#对从右往左逆序数字进行加和判断
if newrightmax > 0:
newrightmax += strnums[i]
else:
newrightmax = strnums[i]
rightmax.append(max(newrightmax, rightmax[-1]))
maxbase = -float("inf")
for i in range(n - 1):
#左边最大+右边最大
new = leftmax[i] + rightmax[n - i - 2]
if maxbase < new:
maxbase = new
return maxbase