Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Potions (Hard Version)

#include <bits/stdc++.h>
using namespace std;

void solve(vector<int> &a) {
    int n = a.size();
    priority_queue<long long> abs_of_neg;

    long long pref = 0;
    int ans = 0;
    for (int i = 0; i < n; i++) {
        int x = a[i];
        if (x >= 0) {
            pref += x;
            ans++;
        } else {
            if (pref - abs(x) >= 0) {
                pref -= abs(x);
                ans++;
                abs_of_neg.push(abs(x));
            } else if (!abs_of_neg.empty() && abs_of_neg.top() > abs(x)) {
                auto old = abs_of_neg.top();
                abs_of_neg.pop();

                pref += abs(old);
                pref -= abs(x);
                abs_of_neg.push(abs(x));
            }
        }
    }
    cout << ans << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    solve(a);

    return 0;
}