#B4298. Magic Staffs Equalization

    ID: 11954 Type: Default 1000ms 256MiB

Magic Staffs Equalization

Magic Staffs Equalization

Wukong has conjured up $N$ magical staffs with distinct heights in the range $[1,1000]$, arranged in a row. In one spell, he can increase or decrease the height of a single staff by $1$. Now, he wishes to make $K$ consecutive staffs have the same height using a minimum number of spells.

For any contiguous segment of $K$ staffs with heights $h_1, h_2, \dots, h_K$, you can change each height to an integer target $T$. The cost for a staff with height $h_i$ is $|h_i-T|$. It is well known that to minimize the sum $\sum_{i=1}^{K} |h_i-T|$, the optimal choice for $T$ is the median of the segment.

Determine the minimum number of operations required such that there exists a contiguous segment of $K$ staffs that all have the same height.

inputFormat

The first line contains two integers $N$ and $K$ ($1 \leq K \leq N$), where $N$ is the number of staffs.

The second line contains $N$ space-separated integers, each representing the height of a staff. All heights are distinct and fall in the range $[1, 1000]$.

outputFormat

Output a single integer, the minimum number of spells required to make $K$ consecutive staffs have the same height.

sample

3 2
3 6 1
3