from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,datetime sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inpl(): return list(map(int, input().split())) def inpls(): return list(input().split()) N,K = inpl() aa = inpl() x0 = 0 x3 = 10**9+10 x1 = (x0*2+x3)//3 x2 = (x0+x3*2)//3 def f(m): aa_dush = list(map(lambda x:abs(x-m), aa)) l = 0 tmp = sum(aa_dush[:K]) ans = tmp for r in range(K,N): tmp += aa_dush[r] tmp -= aa_dush[l] ans = min(tmp,ans) l += 1 return ans for i in range(50): y1 = f(x1) y2 = f(x2) if y1 > y2: x0 = x1 else: x3 = x2 x1 = (x0*2+x3)//3 x2 = (x0+x3*2)//3 print(min(f(x0),y1,y2,f(x3)))