Maximum Sum Subarray with Length ConstraintHard

Maximum Sum Subarray with Length Constraint

HardPractice library · +30 XPdynamic programmingarraysoptimization

Given an array of N integers A and an integer K, find a subarray A[i..j] such that j - i + 1 <= K and the sum of its elements is maximized. If multiple subarrays yield the same maximum sum, choose the one with the smallest starting index i. If there's still a tie, choose the one with the smallest ending index j.

Input

The first line contains two integers N and K. The second line contains N integers A_1, A_2, ..., A_N.

Output

Print a single integer: the maximum sum achievable under the given constraints.

Constraints

1 <= N <= 200000, 1 <= K <= N, -10^9 <= A_i <= 10^9

Time limit 2 s (native code; slower languages get more)Memory 256 MB16 hidden tests

Example 1

Input
5 3
1 -2 3 4 -5
Output
7

The subarray [3, 4] has sum 7 and length 2 <= 3. This is the maximum possible sum.

Example 2

Input
7 2
5 -1 4 -2 3 0 1
Output
5

The subarray [5] has sum 5 and length 1 <= 2. The subarray [4] has sum 4. The subarray [5, -1] has sum 4 and length 2 <= 2. Max sum is 5.

Hints