class fenwick_tree(object): def __init__(self, n): self.n = n self.log = n.bit_length() self.data = [0] * n def __sum(self, r): s = 0 while r > 0: s += self.data[r - 1] r -= r & -r return s def add(self, p, x): """ a[p] += xを行う""" p += 1 while p <= self.n: self.data[p - 1] += x p += p & -p def sum(self, l, r): """a[l] + a[l+1] + .. + a[r-1]を返す""" return self.__sum(r) - self.__sum(l) def lower_bound(self, x): """a[0] + a[1] + .. a[i] >= x となる最小のiを返す""" if x <= 0: return -1 i = 0 k = 1 << self.log while k: if i + k <= self.n and self.data[i + k - 1] < x: x -= self.data[i + k - 1] i += k k >>= 1 return i def show(self): for i in range(self.n): print(self.__sum(i+1) if not i else self.sum(i, i+1), end=" ") print() N, K = map(int, input().split()) A = list(map(int, input().split())) if K == 1: print(0) exit() Aset = sorted(set(A)) atoi = {a: i for i, a in enumerate(Aset)} bit_cnt = fenwick_tree(N) bit_val = fenwick_tree(N) for i in range(K - 1): a = A[i] p = atoi[a] bit_cnt.add(p, 1) bit_val.add(p, a) ans = 10 ** 18 for i in range(K - 1, N): a = A[i] p = atoi[a] bit_cnt.add(p, 1) bit_val.add(p, a) mid = bit_cnt.lower_bound((K + 1) // 2) a = Aset[mid] cost = a * bit_cnt.sum(0, mid) - bit_val.sum(0, mid) cost += bit_val.sum(mid + 1, N) - a * bit_cnt.sum(mid + 1, N) ans = min(ans, cost) a = A[i - K + 1] p = atoi[a] bit_cnt.add(p, -1) bit_val.add(p, -a) print(ans)