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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 500010;

using ll = long long int;
const int POT = 512 * 1024;
ll tree[2 * POT + 10];

void tree_set(int x, ll v) {
    x += POT - 1;
    tree[x] = max(tree[x], v);
    x >>= 1;
    while (x >= 1) {
        tree[x] = max(tree[x << 1], tree[(x << 1) + 1]);
        x >>= 1;
    }
}

ll tree_get(int a) {
    a += POT - 1;
    ll out = tree[a];
    while (a > 1) {
        if (a & 1) out = max(out, tree[a - 1]);
        a >>= 1;
    }
    return out;
}


ll a[MAXN];
pair<ll, int> S[MAXN];
int pos[MAXN];

int main() {
    int n;
    scanf("%d", &n);
    
    for (int i = 1; i <= n; i++) {
        scanf("%lld", a + i);
        S[i].first = S[i - 1].first + a[i];
        S[i].second = i;
    }
    
    if (S[n].first < 0) {
        printf("-1\n");
        return 0;
    }
    
    sort(S + 1, S + 1 + n);
    int j = 0;
    for (int i = 1; i <= n; i++) {
        if (S[i].first < 0) {
            j++;
        }
        else {
            if (i > 1 && S[i].first == S[i - 1].first)
                j++;
            pos[S[i].second] = i - j;
        }
    }
    
    
    ll dp = 0;
    for (int i = 1; i <= n; i++) {
        if (pos[i] == 0)
            continue;
        
        dp = tree_get(pos[i]) + 1;
        tree_set(pos[i], dp);
    }
    
    printf("%lld\n", n - dp);
    return 0;
}