#include #include #include #include #include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; class MedianTracker{ public: ll sum_l = 0; ll sum_r = 0; int size = 0; void push(ll x){ if(str.empty()){ str.insert(x); sum_r += x; }else{ if(median() > x) { stl.insert(x); sum_l += x; }else{ str.insert(x); sum_r += x; } } size++; balance(); } void pop(ll x){ if(stl.find(x) != stl.end()) { stl.erase(stl.find(x)); sum_l -= x; }else{ str.erase(str.find(x)); sum_r -= x; } size--; balance(); } ll median(){ return *str.begin(); } private: void balance(){ while(*str.begin() < *stl.begin()){ ll x = *stl.begin(); stl.erase(stl.begin()); str.insert(x); sum_l -= x; sum_r += x; } while(2*str.size() < size){ ll x = *stl.begin(); stl.erase(stl.begin()); str.insert(x); sum_l -= x; sum_r += x; } while(2*str.size() > size+1){ ll x = *str.begin(); str.erase(str.begin()); stl.insert(x); sum_l += x; sum_r -= x; } } multiset> stl; multiset str; }; const ll INF = 1e18; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int n, k; cin >> n >> k; vector a(n); for(int i = 0; i < n; i++) cin >> a[i]; auto mt = MedianTracker(); ll ans = INF; for(int i = 0; i < k; i++) mt.push(a[i]); // cout << mt.median() << ' ' << mt.sum_l << ' ' << mt.sum_r << endl; int l = k/2, r = k-l; chmin(ans, mt.median()*l-mt.sum_l + mt.sum_r-mt.median()*r); for(int i = k; i < n; i++){ mt.push(a[i]); mt.pop(a[i-k]); chmin(ans, mt.median()*l-mt.sum_l + mt.sum_r-mt.median()*r); // cout << mt.median() << ' ' << mt.sum_l << ' ' << mt.sum_r << endl; } cout << ans << endl; }