#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; }; template class Tree { private: int d; vector> v; public: Tree(int dd) { // インデックスを d ビットの非負整数とする d = dd; v.PB({ 0, 0, 0 }); } 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) { // a[x] += y して sum [0, x) を返す int p = 0; T sum = 0; dec(i, d) { bool is_l = ! ((x >> i) & 1); if(is_l) { v[p].s += y; } else { sum += v[p].s; } int & ref (is_l ? v[p].l : v[p].r); if(ref == 0) { if(y == 0) { return sum; } ref = v.size(); v.PB({ 0, 0, 0 }); } 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[p].s > s) { p = v[p].l; } else { p = v[p].r; sum += v[p].s; x += 1LL << i; } } return x; } }; // ---- LL n, k, a[100000]; int main() { cin >> n >> k; inc(i, n) { cin >> a[i]; } Tree tc(30); Tree ts(30); 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 = 1e9 + 1; 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)); LL y = a[i - k + 1]; tc.add(y, -1); ts.add(y, -y); } } cout << ans << endl; return 0; }