#ifndef LOCAL #include using namespace std; #define debug(...) (void(0)) #else #include "algo/debug.h" #endif template struct FenwickTree { private: int n; int pw; std::vector dat; public: FenwickTree(int m = 0) { init(m); } void init(int m) { n = m; pw = std::bit_floor((unsigned int)n); dat.assign(n, T{}); } void add(int p, const T& x) { assert(0 <= p && p < n); for (p += 1; p <= n; p += p & -p) { dat[p - 1] += x; } } T sum(int l, int r) const { assert(0 <= l && l <= r && r <= n); return sum(r) - sum(l); } int select(T x) const { int at = 0; for (int len = pw; len > 0; len >>= 1) { if (at + len <= n && dat[at + len - 1] <= x) { at += len; x -= dat[at - 1]; } } assert(0 <= at && at <= n); return at; } private: T sum(int r) const { T ans{}; for (; r > 0; r -= r & -r) { ans += dat[r - 1]; } return ans; } }; void solve() { int N, K; cin >> N >> K; vector A(N); for (int i = 0; i < N; i++) cin >> A[i]; vector cc; for (const auto& x : A) cc.push_back(x); sort(cc.begin(), cc.end()); cc.erase(unique(cc.begin(), cc.end()), cc.end()); FenwickTree st(N); FenwickTree fw(N); const auto Add = [&](int p, int x, int64_t a) { int y = distance(cc.begin(), lower_bound(cc.begin(), cc.end(), p)); st.add(y, x); fw.add(y, a); }; int64_t ans = 1e18; int64_t sum = 0; for (int i = 0; i < N; i++) { if (i < K - 1) { Add(A[i], 1, A[i]); sum += A[i]; } else { Add(A[i], 1, A[i]); sum += A[i]; int id = st.select(K / 2); int64_t res = int64_t(2 * st.sum(0, id) - K) * cc[id] + sum - 2LL * fw.sum(0, id); ans = min(ans, res); Add(A[i - K + 1], -1, -A[i - K + 1]); sum -= A[i - K + 1]; } } cout << ans << endl; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int tt = 1; // std::cin >> tt; while (tt--) { solve(); } }