class Fenwick_Tree: def __init__(self, n): self._n = n self.data = [0] * n def add(self, p, x): assert 0 <= p < self._n p += 1 while p <= self._n: self.data[p - 1] += x p += p & -p def sum(self, l, r): assert 0 <= l <= r <= self._n return self._sum(r) - self._sum(l) def _sum(self, r): s = 0 while r > 0: s += self.data[r - 1] r -= r & -r return s def get(self, k): k += 1 x, r = 0, 1 while r < self._n: r <<= 1 len = r while len: if x + len - 1 < self._n: if self.data[x + len - 1] < k: k -= self.data[x + len - 1] x += len len >>= 1 return x from bisect import * from copy import * def compress(lst): B = [] D = dict() vals = deepcopy(lst) vals = list(set(vals)) vals.sort() for i in range(len(lst)): ind = bisect_left(vals, lst[i]) B.append(ind) for i in range(len(B)): D[lst[i]] = B[i] return B, D, vals N, K = map(int, input().split()) A = list(map(int, input().split())) + [-1] A, _, itov = compress(A) Ts = Fenwick_Tree(N + 5) Tn = Fenwick_Tree(N + 5) for i in range(K): Ts.add(A[i], itov[A[i]]) Tn.add(A[i], 1) ind = Tn.get(K//2) ans = Ts.sum(ind + 1, N + 5) - Ts.sum(0, ind) + itov[ind] * (Tn.sum(0, ind) - Tn.sum(ind+1, N + 5)) for i in range(K, N): Ts.add(A[i-K], -itov[A[i-K]]) Ts.add(A[i], itov[A[i]]) Tn.add(A[i-K], -1) Tn.add(A[i], 1) ind = Tn.get(K//2) val = itov[ind] ans = min(ans, Ts.sum(ind + 1, N + 5) - Ts.sum(0, ind) + val * (Tn.sum(0, ind) - Tn.sum(ind+1, N + 5))) print(ans)