def f(k): b = A[k] L = sorted([abs(a - b) for a in A]) return sum(L[:K]) - sum(L[K:]) N, K = map(int, input().split()) A = [int(a) for a in input().split()] # 1 l, r = 0, N - 1 fl, fr = f(l), f(r) ans = min(fl, fr) while r - l > 2: m1 = (l * 2 + r) // 3 m2 = (l + r * 2) // 3 fm1, fm2 = f(m1), f(m2) if fm1 < fm2: r = m2 ans = min(ans, fm1) else: l = m1 ans = min(ans, fm2) if r - l > 1: ans = min(ans, f(l + r >> 1)) # 2 mi = 10 ** 60 mii = -1 s = max(1, N // 500) for i in range(0, N, s): fi = f(i) if fi < mi: mi = fi mii = i ans = min(ans, mi) l = max(0, mii - s) r = min(N, mii + s) while r - l > 3: m1 = (l * 2 + r) // 3 m2 = (l + r * 2) // 3 fm1, fm2 = f(m1), f(m2) if fm1 < fm2: r = m2 ans = min(ans, fm1) else: l = m1 ans = min(ans, fm2) if r - l > 1: for i in range(l + 1, r): ans = min(ans, f(i)) print(ans)