#include <bits/stdc++.h>
using namespace std;
long long n, k, i, j, m, a[200008], c[200008];
int main() {
  for (scanf("%I64d%I64d", &n, &k); i++ < n; scanf("%I64d", a + i))
    ;
  for (sort(a + 1, a + n + 1), i = 0; i++ < n; c[i] = c[i - 1] + a[i])
    ;
  for (i = n - k; i++ < n; m += a[i] - a[n + 1 - k])
    ;
  for (i = n + 1 - k; a[n + 1 - k] == a[--i]; --m)
    ;
  for (i = 0; i++ < k; j += a[k] - a[i])
    ;
  for (i = k; a[k] == a[++i]; --j)
    ;
  for (j < m ? m = j : 0, i = 1; i <= n && 0 < m;
       j < i + k ? m = min(m, c[n] - (c[i] << 1) + a[i] * (i + i - n) + k - n)
                 : m = 0,
               i = j)
    for (j = i; a[i] == a[++j];)
      ;
  printf("%I64d\n", m < 0 ? 0 : m), exit(0);
}
