1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 500003;
int n, a[N];
long long sum, suf[N];
vector<long long> v;
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n;
    for (int i=0; i<n; i++) cin >> a[i];
    for (int i=n-1; i>=0; i--) suf[i] = suf[i+1] + a[i];
    if (suf[0] < 0) {
        cout << "-1\n";
        return 0;
    }
    for (int i=0; i<n; i++) {
        sum += a[i];
        if (sum < 0 || suf[i+1] < 0) continue;
        if (v.empty() || sum >= v.back()) {
            v.push_back(sum);
            continue;
        }
        int beg = 0, end = v.size();
        while (beg < end) {
            int cen = (beg + end) / 2;
            if (v[cen] <= sum) beg = cen+1; else end = cen;
        }
        v[beg] = sum;
    }
    cout << n - v.size() << "\n";
    return 0;
}