#include using namespace std; template ostream &operator<<(ostream &os, const pair &p) { os << "(" << p.first << "," << p.second << ")"; return os; } #ifdef __LOCAL #define debug(x) cerr << __LINE__ << ": " << #x << " = " << x << endl #define debugArray(x, n) \ cerr << __LINE__ << ": " << #x << " = {"; \ for (long long hoge = 0; (hoge) < (n); ++(hoge)) \ cerr << ((hoge) ? "," : "") << x[hoge]; \ cerr << "}" << endl #else #define debug(x) (void(0)) #define debugArray(x, n) (void(0)) #endif #define TEST(s) \ if (!(s)) { \ cout << __LINE__ << " " << #s << endl; \ exit(-1); \ } double tick() { static clock_t oldtick; clock_t newtick = clock(); double diff = 1.0 * (newtick - oldtick) / CLOCKS_PER_SEC; oldtick = newtick; return diff; } template struct BinaryIndexedTree { vector dat; BinaryIndexedTree(int n) : dat(n + 1, 0) {} BinaryIndexedTree(int n, T a) : BinaryIndexedTree(vector(n, a)) {} BinaryIndexedTree(vector y) : dat(y.size() + 1) { for (int i = 0; i < y.size(); ++i) dat[i + 1] = y[i]; for (int i = 1; i + (i & -i) < dat.size(); ++i) dat[i + (i & -i)] += dat[i]; } void add(int i, T a = 1) { for (++i; i < (int)dat.size(); i += i & -i) dat[i] += a; } T sum(int i) { // sum [0,i) T s = 0; for (; i > 0; i &= i - 1) s += dat[i]; return s; } // min { i : sum(i+1) > k } -> kth element(0-indexed) int find(T k) const { int i = 0; for (int p = 1 << (__lg(dat.size() - 1) + 1); p > 0; p >>= 1) if (i + p < (int)dat.size() && dat[i + p] <= k) k -= dat[i += p]; return i + 1 == (int)dat.size() ? -1 : i; // -1 -> no solutions } }; signed main() { cin.tie(0); ios::sync_with_stdio(0); int N, K; cin >> N >> K; long long A[N]; for (int i = 0; i < N; i++) cin >> A[i]; vector vec(A, A + N); sort(vec.begin(), vec.end()); vec.erase(unique(vec.begin(), vec.end()), vec.end()); auto id = [&](int x) { return lower_bound(vec.begin(), vec.end(), x) - vec.begin(); }; BinaryIndexedTree bit1(vec.size()), bit2(vec.size()); long long ans = LLONG_MAX / 10; long long sum = 0; for (int i = 0; i < N; i++) { int idx = id(A[i]); bit1.add(idx, 1); bit2.add(idx, A[i]); sum += A[i]; if (i >= K - 1) { int med = bit1.find(K / 2); int lcnt = bit1.sum(med), hcnt = K - lcnt; long long lsum = bit2.sum(med), hsum = sum - lsum; long long low = lcnt * vec[med] - lsum; long long high = hsum - hcnt * vec[med]; ans = min(ans, low + high); int jdx = id(A[i - K + 1]); bit1.add(jdx, -1); bit2.add(jdx, -A[i - K + 1]); sum -= A[i - K + 1]; } } cout << ans << "\n"; return 0; }