LeetCode 689 Maximum Sum of 3 Non-Overlapping Subarrays

In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum.

Each subarray will be of size k, and we want to maximize the sum of all 3*k entries.

Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.

Example:

Input: [1,2,1,2,6,7,5,1], 2
Output: [0, 3, 5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.

Note:

nums.length will be between 1 and 20000.
nums[i] will be between 1 and 65535.
k will be between 1 and floor(nums.length / 3).

找出数组中三个不重叠的子数组,子数组长度k,且子数组总和最大。

碰见数组和的题目就可以想想DP。题目说了三个子数组,这个三有什么特点呢,就是左,中,右。假设中间数组是以第i个元素结尾的子数组。那么此时最大和就是中间子数组+i左边最大子数组+i右边最大子数组。假设为sum(i)。遍历数组找到最大sum(i)即可。

class Solution(object):
    def maxSumOfThreeSubarrays(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        sums = [sum(nums[0:k])]
        for i in range(1, len(nums) - k + 1):
            sums.append(sums[i-1]-nums[i-1]+nums[i+k-1])
        left = [0 for _ in range(len(sums))]
        left_max = 0
        for i in range(0,len(left)):
            if sums[i] > sums[left_max]:
                left_max = i
            left[i] = left_max
        right = [0 for _ in range(len(sums))]
        right_max = len(sums)-1
        for i in range(len(right)-1,-1,-1):
            if sums[i] > sums[right_max]:
                right_max = i
            right[i] = right_max
        max_cur = 0
        res = []
        for i in range(k, len(nums) - 2 * k + 1):
            a = left[i-k]
            b = right[i+k]
            t = sums[a] + sums[b] + sums[i]
            if t > max_cur:
                max_cur = t
                res = [a, i, b]
        return res

点赞