#include using namespace std; using ll = long long; //引数unzipには圧縮前のvectorを入れる int compress(vector& unzip, map& zip) { sort(unzip.begin(), unzip.end()); unzip.erase(unique(unzip.begin(), unzip.end()), unzip.end()); for (int i = 0; i < unzip.size(); i++) { zip[unzip[i]] = i; } return unzip.size(); } //1-indexであることに注意 template struct BIT { int n; vector data; BIT(int n) : n(n), data(n + 1, 0) {} T sum(int i) { T s = 0; while (i > 0) { s += data[i]; i -= i & -i; } return s; } void add(int i, T x) { while (i <= n) { data[i] += x; i += i & -i; } } }; int main() { cin.tie(0); ios::sync_with_stdio(false); int n, k; cin >> n >> k; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector unzip(a); map zip; compress(unzip, zip); BIT b(unzip.size()); BIT b2(unzip.size()); ll ans = 1000000000000000LL; for (int i = 0; i < n; i++) { b.add(zip[a[i]] + 1, 1); b2.add(zip[a[i]] + 1, a[i]); if (i < k - 1) continue; if (i >= k) { b.add(zip[a[i - k]] + 1, -1); b2.add(zip[a[i - k]] + 1, -a[i - k]); } int ok = (int)unzip.size() - 1, ng = -1; while (ok - ng > 1) { int mid = (ok + ng) / 2; if (b.sum(mid + 1) >= (k + 1) / 2) ok = mid; else ng = mid; } ll hoge = b2.sum(unzip.size()) - b2.sum(ok + 1); ll foo = b.sum(unzip.size()) - b.sum(ok + 1); ll tmp = hoge - foo * unzip[ok]; hoge = b2.sum(ok); foo = b.sum(ok); tmp += foo * unzip[ok] - hoge; ans = min(ans, tmp); //cout << unzip[ok] << endl; } cout << ans << endl; return 0; }