/* -*- coding: utf-8 -*- * * 3646.cc: No.3646 Decrement. - yukicoder */ #include #include #include using namespace std; /* constant */ const int MAX_N = 200000; /* typedef */ using ll = long long; struct Node { int a, l, u; bool f; Node *prv, *nxt; Node(int _a = 0, int _l = 0, int _u = 0, bool _f = false, Node *_prv = nullptr, Node *_nxt = nullptr): a(_a), l(_l), u(_u), f(_f), prv(_prv), nxt(_nxt) {} Node *lmerge() { if (prv != nullptr && a == prv->a) { prv->f = true; u = prv->u, l += prv->l; prv = prv->prv; if (prv != nullptr) prv->nxt = this; } return this; } Node *rmerge() { if (nxt != nullptr && a == nxt->a) { nxt->f = true; l += nxt->l; nxt = nxt->nxt; if (nxt != nullptr) nxt->prv = this; } return this; } }; struct CompNode { bool operator()(const Node *a, const Node *b) const { return a->l > b->l; } }; /* global variables */ int as[MAX_N + 2]; Node *es[MAX_N + 2]; /* subroutines */ /* main */ int main() { int n; ll k; scanf("%d%lld", &n, &k); for (int i = 1; i <= n; i++) scanf("%d", as + i); as[0] = as[n + 1] = 0; priority_queue,CompNode> q; for (int i = 1; i <= n;) { int j = i; while (i <= n && as[j] == as[i]) i++; auto e = new Node(as[j], i - j, j); es[j] = es[i - 1] = e; if (as[j - 1] < as[j] && as[i - 1] > as[i]) q.push(e); } es[0] = new Node(0, 1, 0); es[n + 1] = new Node(0, 1, n + 1); for (int i = 0; i <= n; i++) if (es[i] != es[i + 1] && es[i] != nullptr && es[i + 1] != nullptr) { es[i]->nxt = es[i + 1], es[i + 1]->prv = es[i]; } while (k > 0 && ! q.empty()) { auto e = q.top(); q.pop(); if (e->l > k) break; if (e->f) continue; int maxa = max(e->prv != nullptr ? e->prv->a : 0, e->nxt != nullptr ? e->nxt->a : 0); int da = min(k / e->l, (ll)e->a - maxa); e->a -= da; k -= (ll)da * e->l; e->lmerge(); e->rmerge(); if (e->a > 0 && e->prv->a < e->a && e->a > e->nxt->a) q.push(e); } Node *rt = nullptr; for (int i = 0; i <= n + 1; i++) if (es[i] != nullptr && ! es[i]->f) { rt = es[i]; break; } ll sum = 0; while (rt != nullptr && rt->nxt != nullptr) { sum += abs(rt->nxt->a - rt->a); rt = rt->nxt; } printf("%lld\n", sum); return 0; }