Solution
Let
Suppose we choose a segment [l,r] of length . Then
The cost of this segment is
We split all positions into three cases.
If i < l, then d_i = l-i, therefore
So the contribution of these positions is
If l \le i \le r, then d_i=0, so the contribution is
If i>r, then d_i=i-r, therefore
So the contribution is
Therefore, the total cost of [l,r] is
The segment must satisfy
Since r=l+k-1, it is enough to iterate over
There are possible segments.
For every segment, we iterate over all positions and directly calculate its cost in time.
Thus, the whole solution works in O(n^2).
Since the answer can be much larger than 2^{31}, we need to use long long.
Correctness
For every valid segment [l,r], we calculate exactly
by separately considering the cases i<l, l\le i\le r, and i>r.
These three cases cover every position exactly once.
We check every valid segment of length , so the minimum value found by the algorithm is exactly the required answer.
Complexity
There are possible segments, and every segment is processed in time.
Therefore, the total complexity is
time and
memory.