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
77
78
#include <iostream>
#include <queue>
using namespace std;

int n;
long t[500000];
int find_left(int index){
    //vector<int>p;
    long power=0;
    for (int i = index-1; i >=0; i--)
    {
        //cout<<t[i]<<endl;
        //if(t[i]>0)
            power+=t[i];
            //p.push_back(t[i]);
        if(power>=-t[index])
            return index-i;
    }
    return 0-1;
}
vector<int> find_right(int index){
    vector<int>p;
    long power=0;
    for (int i = index+1; i < n; i++)
    {
        //if(t[i]>0)
            power+=t[i];
            p.push_back(t[i]-power);
        if(power>=-t[index])
            return p;
    }
    p.resize(0);
    return p;
}
int main(){
    int length=0;
    int left;
    vector<int>right;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>t[i];
    }
    for(int i=0;i<n;i++){
        if(t[i]<0){
            left=find_left(i);
            right=find_right(i);
            //cout<<i<<" "<<left<<" "<<right<<endl;
            if(left==-1&&right.size()==0){
                cout<<-1;
                return 0;
            }
            else if(left==-1){
                length+=right.size();
                for (int j = i; j < i+right.size(); j++)
                {
                   t[j]+=right[j-i];
                }
                
            }
            else if(right.size()==0)
                length+=left;
            else{
                if(left<right.size())
                    length+=left;
                else
                {
                    length+=right.size();
                    for (int j = i; j < i+right.size(); j++)
                    {
                    t[j]+=right[j-i];
                    }
                }
            }
        }
    }
    cout<<length;
    return 0;
}