using System; using static System.Console; using System.Linq; using System.Collections.Generic; class Program { static int NN => int.Parse(ReadLine()); static long[] NList => ReadLine().Split().Select(long.Parse).ToArray(); public static void Main() { Solve(); // Test(); } static void Test() { var r = new Random(); var count = 0; while (true) { var n = 5; var k = r.Next(n + 1); var a = new long[n]; for (var i = 0; i < n; ++i) a[i] = r.Next(-3, 3); Array.Sort(a); // 愚直解 var s1 = All(n, k, a); // 作成解 var s2 = Abs(n, k, a); if (s1 != s2) { WriteLine(n + " " + k); // WriteLine(string.Join("\n", map.Select(m => string.Join(" ", m)))); WriteLine(string.Join(" ", a)); WriteLine(s1); WriteLine(s2); return; } ++count; if (count % 1000 == 0) WriteLine(count); } } static long All(int n, int k, long[] a) { var ans = long.MaxValue; for (var i = 0; i <= n - k; ++i) for (var x = 0; x < n; ++x) { var sub = 0L; for (var p = 0; p < n; ++p) { var abs = Math.Abs(a[x] - a[p]); if (p < i || p >= i + k) sub -= abs; else sub += abs; } ans = Math.Min(ans, sub); } return ans; } static void Solve() { var c = NList; var (n, k) = ((int)c[0], (int)c[1]); var a = NList; WriteLine(Abs(n, k, a)); } static long Abs(int n, int k, long[] a) { var cum = new long[n + 1]; for (var i = 0; i < n; ++i) cum[i + 1] = cum[i] + a[i]; var ans = long.MaxValue; if (k == 0) { ans = Math.Min(a[0] * n - cum[n], cum[n] - a[^1] * n); } else if (k == n) { ans = a[n / 2] * (n / 2) - cum[n / 2] + cum[n] - cum[n / 2] - a[n / 2] * (n - n / 2); } else { var pos = (2 * k - n - 1) / 2; for (var i = 0; i <= n - k; ++i) { var x = Math.Max(0, Math.Min(n - 1, pos)); ans = Math.Min(ans, cum[i] - a[x] * i + a[x] * (x - i) - cum[x] + cum[i] + cum[k + i] - cum[x] - a[x] * (k + i - x) + a[x] * (n - k - i) - cum[n] + cum[k + i]); pos += 2; } } return ans; } }