#include using namespace std; typedef long long signed int LL; typedef long long unsigned int LU; #define incID(i, l, r) for(int i = (l) ; i < (r); i++) #define incII(i, l, r) for(int i = (l) ; i <= (r); i++) #define decID(i, l, r) for(int i = (r) - 1; i >= (l); i--) #define decII(i, l, r) for(int i = (r) ; i >= (l); i--) #define inc(i, n) incID(i, 0, n) #define inc1(i, n) incII(i, 1, n) #define dec(i, n) decID(i, 0, n) #define dec1(i, n) decII(i, 1, n) #define inII(v, l, r) ((l) <= (v) && (v) <= (r)) #define inID(v, l, r) ((l) <= (v) && (v) < (r)) #define PB push_back #define EB emplace_back #define MP make_pair #define FI first #define SE second #define PQ priority_queue #define ALL(v) v.begin(), v.end() #define RALL(v) v.rbegin(), v.rend() #define FOR(it, v) for(auto it = v.begin(); it != v.end(); ++it) #define RFOR(it, v) for(auto it = v.rbegin(); it != v.rend(); ++it) template bool setmin(T & a, T b) { if(b < a) { a = b; return true; } else { return false; } } template bool setmax(T & a, T b) { if(b > a) { a = b; return true; } else { return false; } } template bool setmineq(T & a, T b) { if(b <= a) { a = b; return true; } else { return false; } } template bool setmaxeq(T & a, T b) { if(b >= a) { a = b; return true; } else { return false; } } template T gcd(T a, T b) { return (b == 0 ? a : gcd(b, a % b)); } template T lcm(T a, T b) { return a / gcd(a, b) * b; } // ---- ---- template struct Node { T s; int l, r; }; // とにかくひどい const int D = 30; const int Q = 200000; Node v[2][D * Q]; int cnt; template class Tree { private: int z; // vector> v; public: Tree(int zz) { z = zz; cnt = 1; } T insert(T x) { return add(x, 1); } T erase(T x) { return add(x, -1); } T rank(T x) { return add(x, 0); } T add(T x, T y) { // v[x] += y して sum [0, x) を返す int p = 0; T sum = 0; dec(i, D) { bool is_l = ! ((x >> i) & 1); if(is_l) { v[z][p].s += y; } else { sum += v[z][p].s; } int & ref (is_l ? v[z][p].l : v[z][p].r); if(ref == 0) { if(y == 0) { return sum; } // ref = v.size(); // v.PB({ 0, 0, 0 }); ref = cnt; cnt++; } p = ref; } return sum; } T find(T s) { // sum[0, x) <= s となる最大の x を返す(最大値を投げると死ぬ気がする) int p = 0; T sum = 0, x = 0; dec(i, D) { if(sum + v[z][p].s > s) { p = v[z][p].l; } else { sum += v[z][p].s; p = v[z][p].r; x += 1LL << i; } assert(p != 0); } return x; } }; // ---- // なんか n < 1600 くらいまでしかうまく動かない LL n, k, a[100000]; int main() { cin >> n >> k; inc(i, n) { cin >> a[i]; } Tree tc(0); Tree ts(1); LL INF = 1e9 + 1; tc.insert(INF); ts.insert(INF); LL ans = 1e15; inc(i, n) { LL x = a[i]; tc.add(x, 1); ts.add(x, x); if(i >= k - 1) { LL M = tc.find(k / 2); LL H = INF; LL lc = tc.rank(M); LL ls = ts.rank(M); LL hc = tc.rank(H) - lc; LL hs = ts.rank(H) - ls; setmin(ans, (M * lc - ls) + (hs - M * hc)); // cout << (M * lc - ls) << " + " << (hs - M * hc) << endl; LL y = a[i - k + 1]; tc.add(y, -1); ts.add(y, -y); } } cout << ans << endl; return 0; }