#include #include #include #include using namespace std; const long long INF = 1LL<<60; int n, k; int a[100000]; struct Middler { int n; int mid; multiset pref; multiset suff; long long psum; long long ssum; Middler(const vector &v) { n = v.size(); int j = v.size() / 2; mid = v[j]; psum = 0; for (int i = 0; i < j; i++) { pref.insert(v[i]); psum += v[i]; } ssum = 0; for (int i = j+1; i < n; i++) { suff.insert(v[i]); ssum += v[i]; } } void shiftLeft() { pref.insert(mid); psum += mid; auto itr = suff.begin(); mid = *itr; suff.erase(itr); ssum -= mid; } void shiftRight() { suff.insert(mid); ssum += mid; auto v = pref.end(); mid = *--v; pref.erase(v); psum -= mid; } void normalize() { while (pref.size() < suff.size()) shiftLeft(); while (pref.size() > suff.size() + 1) shiftRight(); } void pop(int x) { if (x == mid) { auto itr = pref.end(); mid = *--itr; pref.erase(itr); psum -= mid; } else if (x < mid) { auto itr = pref.find(x); pref.erase(itr); psum -= x; } else { auto itr = suff.find(x); suff.erase(itr); ssum -= x; } normalize(); } void push(int x) { if (x <= mid) { pref.insert(x); psum += x; } else { suff.insert(x); ssum += x; } normalize(); } void debug(const string &msg) { cout << msg << endl; cout << mid << endl; cout << pref.size() << " " << psum << " "; for (auto &t: pref) cout << t << " "; cout << endl; cout << suff.size() << " " << ssum << " "; for (auto &t: suff) cout << t << " "; cout << endl; } }; int main() { cin >> n >> k; for (int i = 0; i < n; i++) cin >> a[i]; if (k == 1) { cout << 0 << endl; return 0; } vector v(k); for (int i = 0; i < k; i++) v[i] = a[i]; sort(v.begin(), v.end()); Middler middler(v); long long ret = INF; for (int i = 0; i < n; i++) { long long sum = (middler.mid * middler.pref.size() - middler.psum) + (middler.ssum - middler.mid * middler.suff.size()); ret = min(ret, sum); if (i+k >= n) break; middler.pop(a[i]); middler.push(a[i+k]); } cout << ret << endl; return 0; }