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()] l, r = 0, N - 1 fl, fr = f(l), f(r) ans = min(fl, fr) while r - l > 3: m1 = (l * 3 + r) // 4 m2 = (l + r * 3) // 4 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)