LeetCode 689 Maximum Sum of 3 Non-Overlapping Subarrays

22 篇文章 0 订阅
15 篇文章 1 订阅

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值