[SYSU][大二下] 高级编程技术HW Week-9 Lecture-1

Question

在 Leetcode 上做一道题


Answer

689. Maximum Sum of 3 Non-Overlapping Subarrays

'''
LeetCode
Topic: Array

689. Maximum Sum of 3 Non-Overlapping Subarrays

Description:
        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).
'''

class Solution:
    '''
    type nums   : List[int]
    type k      : int
    return type : List[int]
    '''
    def maxSumOfThreeSubarrays(self, nums, k):
        '''
        Solution:
            构造K项和数组sums,sums[i] = sum(nums[i - k + 1 .. i])
            从左向右构造K项和最大值及其下标数组maxa,其元素记为va, ia
            从右向左构造K项和最大值及其下标数组maxb,其元素记为vb, ib
            在[k, nsize - k)范围内枚举中段子数组的起点x
            则3段子数组和 = sums[x] + va + vb
        '''
        size = len(nums)
        nsize = size - k + 1
        sums = [0] * nsize
        maxa = [0] * nsize
        maxb = [0] * nsize
        total = 0
        for x in range(size):
            total += nums[x]
            if x >= k - 1:
                sums[x - k + 1] = total
                total -= nums[x - k + 1]
        maxn, maxi = 0, 0
        for x in range(nsize):
            if sums[x] > maxn:
                maxn, maxi = sums[x], x
            maxa[x] = (maxn, maxi)
        maxn, maxi = 0, nsize - 1
        for x in range(nsize - 1, -1, -1):
            if sums[x] > maxn:
                maxn, maxi = sums[x], x
            maxb[x] = (maxn, maxi)
        ansn, ansi = 0, None
        for x in range(k, nsize - k):
            va, ia = maxa[x - k]
            vb, ib = maxb[x + k]
            if sums[x] + va + vb > ansn:
                ansn = sums[x] + va + vb
                ansi = [ia, x, ib]
        return ansi
结果:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值