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).
分析
没有什么好分析,直接用 dp 暴力拆除
code
class Solution(object):
def maxSumOfThreeSubarrays(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if 3 *k > len(nums):
return -1
n = len(nums)
dp = [[0 for _ in range(n)] for _ in range(4)]
dp[1][k-1] = k-1
dp[2][2*k-1] = (k-1, 2*k-1)
dp[3][3*k-1] = (k-1, 2*k-1, 3*k-1)
helper = [0 for _ in range(n)]
helper[k-1] = sum(nums[:k])
for i in range(k, n):
helper[i] = helper[i-1]+nums[i] - nums[i-k]
dp[1][i] = i if helper[i] > helper[dp[1][i-1]] else dp[1][i-1]
x, y = dp[2][2*k-1]
m2 = helper[x] + helper[y]
for i in range(2*k, n):
v = helper[i] + helper[dp[1][i-k]]
if v > m2:
m2 = v
dp[2][i] = (dp[1][i-k], i)
else:
dp[2][i] = dp[2][i-1]
x, y, z = dp[3][3*k-1]
m3 = helper[x]+helper[y]+helper[z]
for i in range(3*k, n):
x, y = dp[2][i-k]
v = helper[i] + helper[x] + helper[y]
if v > m3:
m3 = v
dp[3][i] = (x, y, i)
else:
dp[3][i] = dp[3][i-1]
return [i+1-k for i in dp[3][-1]]
总结
You are here!
Your runtime beats 39.56 % of python submissions.