cswork / OAOpen practice workspace

AmazonOA #50

Minimize System Cost

Estimated MediumJudge-ready

Topics (AI-labelled)Prefix & RangesTwo Pointers

Remove exactly k contiguous elements; the remaining elements keep their original order, and the cost is the sum of the absolute differences between adjacent elements. Find the minimum cost.

Input

The first line contains n k (1≤k<n≤200000), and the second line contains n values (1..10⁹).

Output

Output a single integer answer.

Example 1

Input:

5 3
3 9 4 2 16

Output:

6

Example 2

Input:

2 1
1 9

Output:

0

Example 3

Input:

4 1
1 4 2 8

Output:

5

Example notes

Example 1: removing the last three elements leaves [3,9] with cost 6, smaller than the other two windows. Example 2: whichever element is removed, only one element remains, so the cost is 0. Example 3: removing the trailing 8 leaves [1,4,2] with cost 3+2=5; removing 4 gives 1+6=7, and no other option is better.

Editorial

Loading solution…