// Full solution, O(N log N). Decompose the skyline into blocks (width w, // h levels) with a monotonic stack; removing one level of a block costs w // operations and saves 2. Take the cheapest levels first. #include using namespace std; typedef long long ll; int main() { int n; ll K; scanf("%d %lld", &n, &K); vector a(n + 2, 0); for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); ll base = 0; // cost / 2 for (int i = 0; i <= n; i++) if (a[i + 1] > a[i]) base += a[i + 1] - a[i]; vector> nodes; // (width, levels) vector> st; // (height, left index) for (int i = 1; i <= n + 1; i++) { ll x = a[i]; int left = i; while (!st.empty() && st.back().first > x) { auto [h, l] = st.back(); st.pop_back(); ll below = x; if (!st.empty()) below = max(below, st.back().first); nodes.push_back({(ll)(i - l), h - below}); left = l; } if (x > 0 && (st.empty() || st.back().first < x)) st.push_back({x, left}); } sort(nodes.begin(), nodes.end()); ll gain = 0; for (auto& [w, h] : nodes) { ll t = min(h, K / w); gain += t; K -= t * w; if (t < h) break; } printf("%lld\n", 2 * (base - gain)); }