import
java.util.*;
class
GFG {
static
int
minimumCost(
int
[] arr,
int
n,
int
k)
{
int
totalcost =
0
;
int
i =
0
, j =
0
;
List<Integer> mp =
new
ArrayList<Integer>();
for
(
int
x =
0
; x < k; x++) {
mp.add(arr[x]);
}
Collections.sort(mp);
if
(k == n) {
int
mid = mp.get(n /
2
- ((k +
1
) %
2
));
int
z = mid;
for
(i =
0
; i < n; i++) {
totalcost += Math.abs(z - arr[i]);
}
return
totalcost;
}
else
{
int
mid = mp.get(k /
2
- ((k +
1
) %
2
));
for
(i = k; i < n; i++) {
int
zz = mid;
int
cost =
0
;
for
(j = i - k; j < i; j++) {
cost += Math.abs(arr[j] - zz);
}
totalcost += cost;
int
idx
= Collections.binarySearch(mp, arr[i]);
if
(idx <
0
) {
mp.add(-idx -
1
, arr[i]);
}
else
{
mp.add(idx, arr[i]);
}
if
(arr[i] < mid) {
mid = mp.get(k /
2
- ((k +
1
) %
2
));
}
if
(arr[i - k] <= mid) {
mid = mp.get(k /
2
- ((k +
1
) %
2
) +
1
);
}
idx = Collections.binarySearch(mp,
arr[i - k]);
if
(idx >=
0
) {
mp.remove(idx);
}
if
(i == n -
1
) {
zz = mid;
cost =
0
;
for
(j = i - k +
1
; j < i +
1
; j++) {
cost += Math.abs(zz - arr[j]);
}
totalcost += cost;
}
}
return
totalcost;
}
}
public
static
void
main(String[] args)
{
int
N =
5
, K =
3
;
int
[] A = {
1
,
2
,
3
,
4
,
6
};
System.out.println(minimumCost(A, N, K));
}
}