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
结果: