#include using namespace std; using ll = long long; using ld = long double; using vl = vector; template using vc = vector; template using vvc = vector>; #define eb emplace_back #define all(x) (x).begin(), (x).end() #define rep(i, n) for (ll i = 0; i < (n); i++) #define repr(i, n) for (ll i = (n)-1; i >= 0; i--) #define repe(i, l, r) for (ll i = (l); i < (r); i++) #define reper(i, l, r) for (ll i = (r)-1; i >= (l); i--) #define repa(i,n) for (auto& i: n) template inline bool chmax(T1 &a, const T2 &b) {if (a inline bool chmin(T1 &a, const T2 &b) {if (b void verr(const set &st) { repa(a, st) cerr << a << " "; cerr << endl; } template void verr(const map &mp) { repa(a, mp) cerr << "{" << a.first << ", " << a.second << "} "; cerr << endl; } template void verr(const vector>& a, const N& n) { rep(i, n) cerr << "{" << a[i].first << ", " << a[i].second << "} "; cerr << endl; } template void verr(const vector& a, const N& n) { rep(i, n) cerr << a[i] << " "; cerr << endl; } ll dbgt = 1; void err() { cerr << "passed " << dbgt++ << endl; } template void err(H&& h,T&&... t){ cerr<< h << (sizeof...(t)?" ":"\n") << flush; if(sizeof...(t)>0) err(forward(t)...); } #endif const ll INF = 4e18; const ld EPS = 1e-11; const ld PI = acos(-1.0L); const ll MOD = 1e9 + 7; // const ll MOD = 998244353; //--------------------------------------------------------------------------------// int main() { ll N, K; cin >> N >> K; vl A(N); rep(i, N) cin >> A[i]; ll ans = 0; vl acc(N + 1); rep(i, N) acc[i + 1] = acc[i] + A[i]; ll d = max((2 * K - N) / 2, 0ll); rep(i, N){ ans += (i < K ? abs(A[i] - A[d]) : -abs(A[i] - A[d])); } if(K == 0){ cout << ans << endl; return 0; } ll res = ans; rep(i, N - K){ if(d == 0){ res += (N - K - i + d + 1 - (K - d - 1) - i) * (A[i + d + 1] - A[i + d]); }else{ d--; } ans += -2 * abs(A[i] - A[i + d + 1]) + 2 * abs(A[i + K] - A[i + d + 1]); ll sa = ((N - K - i - 1) + (d + 1) - (i + 1) - (K - d - 1)) * (d < K - 1 ? A[i + d + 2] - A[i + d + 1] : 0); while(d < K - 1 and sa < 0){ d++; ans += sa; sa = ((N - K - i - 1) + (d + 1) - (i + 1) - (K - d - 1)) * (d < K - 1 ? A[i + d + 2] - A[i + d + 1] : 0); } chmin(res, ans); } cout << res << endl; }