#!/usr/bin/ python3.8 import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines class BinaryIndexedTree(): def __init__(self, seq): self.size = len(seq) self.depth = self.size.bit_length() self.build(seq) def build(self, seq): data = seq size = self.size for i, x in enumerate(data): j = i + (i & (-i)) if j < size: data[j] += data[i] self.data = data def __repr__(self): return self.data.__repr__() def get_sum(self, i): data = self.data s = 0 while i: s += data[i] i -= i & -i return s def add(self, i, x): data = self.data size = self.size while i < size: data[i] += x i += i & -i def find_kth_element(self, k): data = self.data size = self.size x, sx = 0, 0 dx = 1 << (self.depth) for i in range(self.depth - 1, -1, -1): dx = (1 << i) if x + dx >= size: continue y = x + dx sy = sx + data[y] if sy < k: x, sx = y, sy return x + 1 N, K, *A = map(int, read().split()) sortedA = sorted(set(A)) elem_rank = {x: i for i, x in enumerate(sortedA, 1)} bit_num = BinaryIndexedTree([0] * (N + 10)) bit_sum = BinaryIndexedTree([0] * (N + 10)) total = 0 for x in A[:K - 1]: r = elem_rank[x] bit_num.add(r, 1) bit_sum.add(r, x) total += x answer = 10 ** 15 for add_x, rm_x in zip(A[K - 1:], A): add_r = elem_rank[add_x] rm_r = elem_rank[rm_x] bit_num.add(add_r, 1) bit_sum.add(add_r, add_x) total += add_x n = (K + 1) // 2 median_r = bit_num.find_kth_element(n) median = sortedA[median_r - 1] nl = bit_num.get_sum(median_r) nr = K - nl sl = bit_sum.get_sum(median_r) sr = total - sl cost = (nl * median - sl) + (sr - nr * median) if answer > cost: answer = cost bit_num.add(rm_r, -1) bit_sum.add(rm_r, -rm_x) total -= rm_x print(answer)