import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(2*10**5+10) write = lambda x: sys.stdout.write(x+"\n") debug = lambda x: sys.stderr.write(x+"\n") writef = lambda x: print("{:.12f}".format(x)) ### 座標圧縮 (一次元) from bisect import bisect_left def press(l): """xs: ソートした座標値 inds: lの各要素のxsにおけるインデックス """ # xs[inds[i]]==l[i]となる xs = sorted(set(l)) inds = [None] * len(l) # d = {} for i,item in enumerate(l): inds[i] = bisect_left(xs, item) # d[item] = inds[i] return xs, inds class BIT: ### BIT binary def __init__(self, n, values=None): self.bit = [0]*(n+1) self.n = n self.total = 0 if values is not None: for i,v in enumerate(values): self.add(i,v) self.total += v def check(self): l = [] prv = 0 for i in range(1,self.n+1): val = self.query(i) l.append(val-prv) prv = val print(" ".join(map(str, l))) #a1 ~ aiまでの和 O(logn) def query(self,i): res = 0 while i > 0: res += self.bit[i] # res %= M i -= i&(-i) return res def get(self,i): return self.query(i+1) - self.query(i) #ai += x(logN) def add(self,i,x): i += 1 if i==0: raise RuntimeError self.total += x while i <= self.n: self.bit[i] += x # self.bit[i] %= M i += i&(-i) def index(self, v): """a0,...,aiの和がv以上になる最小のindexを求める 存在しないとき配列サイズを返す """ if v <= 0: return 0 if self.total0: if x+ll>1 return x n,k = list(map(int, input().split())) a = list(map(int, input().split())) xs, inds = press(a) m = len(xs) bit = BIT(m) bit2 = BIT(m) total = 0 for i in range(k): bit.add(inds[i], 1) bit2.add(inds[i], xs[inds[i]]) total += a[i] ans = float("inf") for i in range(k,n+1): v = bit.index((k+1)//2) left = bit2.query(v) lnum = bit.query(v) right = total - left - bit2.get(v) rnum = k - lnum - bit.get(v) val = (xs[v]*lnum - left) + (right - xs[v]*rnum) ans = min(ans, val) # bit2.check() # print(left, right) if i==n: break bit.add(inds[i], 1) bit2.add(inds[i], a[i]) bit.add(inds[i-k], -1) bit2.add(inds[i-k], -a[i-k]) total += a[i] - a[i-k] print(ans)