\(dp[i][j]\)表示前\(j\)个元素,选\(i\)个子区间的最优值
对于当前\(j\),转移方程考虑是否以第\(j\)个元素为子区间的最后一个元素
\(dp[i][j] = \max(dp[i][j - 1], dp[i - 1][j - k] + pre[j] - pre[j - k])\)
class Solution:
def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
n, pre = len(nums), [0]
for i in range(n): pre.append(pre[-1] + nums[i])
dp = [[0 for i in range(n + 1)] for j in range(3 + 1)]
for i in range(1, 3 + 1):
for j in range(k, n + 1):
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j - k] + pre[j] - pre[j - k])
# for i in range(3 + 1): print(dp[i])
ans, j, i = [], 3, n
while i > 0:
if j == 0: break
if dp[j][i] > dp[j][i - 1]:
ans.append(i - k)
j = j - 1
i = i - k
else:
i = i - 1
ans.reverse()
return ans