All problems

Problem 903

Constrained Subsequence Sum

Hard · 30 pts · Array, Dynamic Programming, Monotonic Queue

Problem

Choose a non-empty subsequence of the array such that any two consecutive chosen elements are at most K positions apart in the original array. Maximise the sum of the chosen elements. Let best[i] be the best sum of such a subsequence ending at i: it is NUMS[i] plus the largest positive best[j] among the previous K positions (or nothing, if all are negative). A monotonic deque gives that maximum in O(1) amortised.

Input

The first line contains N and K. The second line contains the N values.

Output

Print the maximum subsequence sum.

Constraints

1 <= K <= N <= 100000; -10^4 <= NUMS[i] <= 10^4

Example input

5 2
10 2 -10 5 20

Example output

37

Explanation

For 10 2 -10 5 20 with K = 2, choose 10, 2, 5 and 20: consecutive choices are at most 2 apart (skipping -10), and the sum is 37.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Jump Game VI Next: Maximum Score of a Good Subarray