#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
//#define int ll
#define pb push_back
#define pii pair<int, int>
#define X first
#define Y second
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()

const int MOD = 1e9 + 7;
const int INF = 1e9 + 7;
const int N = 5e5 + 10;

int n, k, a[N];
bool good[N];
pii ts[N];

void solve() {
    cin >> n >> k;
    for(int i = 1; i <= n; ++i) cin >> a[i], ts[i] = {a[i], i};

    sort(ts + 1, ts + n + 1);

    ll sm = 0;
    multiset<int> cur;
    int lst = -1;
    for(int i = n; i > n - k; --i) {
        good[ts[i].Y] = true;
        lst = max(lst, ts[i].Y);
        sm += ts[i].X;
        cur.insert(ts[i].X);
    }
    for(int i = lst + 1; i <= n; ++i) {
        if(i - lst + a[i] > *cur.begin()) {
            sm -= *cur.begin();
            sm += a[i];
            cur.erase(cur.begin());
            cur.insert(a[i]);
            lst = i;
        }
    }

    cout << sm + lst << '\n';
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
#ifdef LOCAL
    freopen("inp.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    auto start = clock();
#endif
    int ttt = 1;
    //cin >> ttt;
    while(ttt--) {
        solve();
    }
#ifdef LOCAL
    auto end = clock();
    cerr << "TIME: " << (end - start) << "ms" << '\n';
#endif
}