#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using i64 = int64_t; using i32 = int32_t; template void init_n(vector& v, size_t n, U x) { v = vector(n, x); } template void init_n(vector& v, size_t n) { init_n(v, n, T()); } template void read_n(vector& v, size_t n, size_t o = 0) { v = vector(n+o); for (size_t i=o; i> v[i]; } template void read_n(T a[], size_t n, size_t o = 0) { for (size_t i=o; i> a[i]; } template T gabs(const T& x) { return max(x, -x); } #define abs gabs i64 n, k; vector a; int main() { cin >> n >> k; read_n(a, n); multiset lq, hq; i64 ans = 1ll << 60, ls = 0, hs = 0; for (i64 i = 0; i < n; ++i) { if (i - k >= 0) { i64 y = a[i - k]; auto lit = lq.find(y); if (lit != lq.end()) { lq.erase(lq.find(y)); ls -= y; } else { hq.erase(hq.find(y)); hs -= y; } } i64 x = a[i]; if (lq.empty() || x <= *(lq.rbegin())) { lq.insert(x); ls += x; } else { hq.insert(x); hs += x; } while (lq.size() < hq.size()) { i64 d = *(hq.begin()); lq.insert(d); hq.erase(hq.begin()); ls += d; hs -= d; } while (lq.size() > hq.size()) { i64 d = *(lq.rbegin()); hq.insert(d); lq.erase(--(lq.end())); hs += d; ls -= d; } if (i + 1 >= k) { i64 med = *(hq.begin()); i64 scr = lq.size() * med - ls + hs - hq.size() * med; ans = min(ans, abs(scr)); } } cout << ans << '\n'; return 0; }