import sys # sys.setrecursionlimit(200005) int1 = lambda x: int(x)-1 pDB = lambda *x: print(*x, end="\n", file=sys.stderr) p2D = lambda x: print(*x, sep="\n", end="\n\n", file=sys.stderr) def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def LI1(): return list(map(int1, sys.stdin.readline().split())) def LLI1(rows_number): return [LI1() for _ in range(rows_number)] def SI(): return sys.stdin.readline().rstrip() # dij = [(0, 1), (-1, 0), (0, -1), (1, 0)] # dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] # inf = (1<<63)-1 inf = (1 << 32)-1 # md = 10**9+7 md = 998244353 from heapq import * class RemovableHeap: def __init__(self): self.hp = [] self.rem = [] self.cnt = {} self.size = 0 self.s = 0 def __len__(self): return self.size def __getitem__(self, i): assert i == 0 self.__trim() return self.hp[0] def push(self, val): heappush(self.hp, val) self.s += val if val in self.cnt: self.cnt[val] += 1 else: self.cnt[val] = 1 self.size += 1 return True def pop(self): self.__trim() assert self.hp self.size -= 1 val = heappop(self.hp) self.s -= val if self.cnt[val] == 1: del self.cnt[val] else: self.cnt[val] -= 1 return val def remove(self, val): if val not in self.cnt: return False self.size -= 1 self.s -= val if self.cnt[val] == 1: del self.cnt[val] else: self.cnt[val] -= 1 heappush(self.rem, val) return True def __trim(self): while self.rem and self.rem[0] == self.hp[0]: heappop(self.hp) heappop(self.rem) def cost(): mid = rr[0] return mid*(k//2)+ll.s+rr.s-mid*(k-k//2) n, k = LI() aa = LI() ll = RemovableHeap() rr = RemovableHeap() pre = sorted(aa[:k]) for a in pre[:k//2]: ll.push(-a) for a in pre[k//2:]: rr.push(a) ans = cost() for i in range(k, n): a = aa[i] if a < rr[0]: ll.push(-a) else: rr.push(a) a = aa[i-k] if a < rr[0]: ll.remove(-a) else: rr.remove(a) if len(ll) < k//2: ll.push(-rr.pop()) if len(ll) > k//2: rr.push(-ll.pop()) ans = min(ans, cost()) print(ans)