能过样例 20pts
#include <bits/stdc++.h>
#define int long long
#define x first
#define y second
using namespace std;
const int N = 3e5 + 5;
typedef pair<int, int> PII;
int n, k;
int a[N], h[N];
struct node{
int pre, nxt, val;
}l[N];
priority_queue<PII> Q;
int ans;
signed main(void) {
cin >> n >> k;
for (int i = 1; i <= n; i ++ ) cin >> a[i];
for (int i = 1; i <= n; i ++ ) {
l[i].val = a[i];
l[i].nxt = i + 1;
l[i].pre = i - 1;
Q.push(make_pair(a[i], i));
}
while (k -- ) {
auto t = Q.top(); Q.pop();
if (h[t.y]) {
k ++;
continue;
}
if (t.x <= 0) break;
ans += t.x;
int left = l[t.y].pre, right = l[t.y].nxt;
h[left] = 1, h[right] = 1;
int u = l[left].val + l[right].val - l[t.y].val;
l[t.y].pre = l[l[t.y].pre].pre, l[t.y].nxt = l[l[t.y].nxt].nxt;
l[l[t.y].pre].nxt = t.y, l[l[t.y].nxt].pre = t.y;
Q.push(make_pair(u, t.y));
}
cout << ans << '\n';
return 0;
}