#include<iostream>
#include<cstdio>
#include<algorithm>
#define LL long long
using namespace std;
const LL inf = 0x7fffffffffffffff;
const int maxn = 1e5 + 10;
int n, k;
LL ans = inf;
LL a[maxn];
int main() {
freopen("qwa.in", "r", stdin);
freopen("qwa.out", "w", stdout);
int i;
cin >> n >> k;
for(i = 1; i <= n; i++)
scanf("%lld", a + i);
sort(a + 1, a + 1 + n);
LL now = 0, sum = 0;
for(i = 1; i <= k; i++) {
now = now + (i - 1)*a[i] - sum;
sum += a[i];
}
for(i = k + 1; i <= n; i++) {
ans = min(ans, now);
sum -= a[i - k];
now -= sum - a[i - k]*(k - 1);
now += a[i]*(k - 1) - sum;
sum += a[i];
}
ans = min(ans, now);
cout << ans << "\n";
return 0;
}