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
79
80
81
#include<bits/stdc++.h>
using namespace std;
void wypis1(vector<pair<int,int>> a)
{
    for(int i = 0; i < (int)a.size(); i++)
    {
        cout<<a[i].first<<" "<<a[i].second<<endl;
    }cout<<endl;
}
void wypis(vector<bool> a)
{
    for(int i = 0; i < (int)a.size(); i++)
    {
        cout<<a[i]<<" ";
    }cout<<endl;
}
int rekur(vector<pair<int,int>> & invest, vector<bool> con, int indeks)
{
    for(int i = 0; i < invest.size(); i++)
    {
        if(invest[i].first < 0)
        {
            int bil_tmp = invest[i].first;
            for(int j = i; j < con.size() && con[j]; j++)
            {
                bil_tmp += invest[j+1].first;
            }
            for(int j = i-1; j > 0 && con[j]; j--)
            {
                bil_tmp += invest[j].first;
            }
            if(bil_tmp < 0)
                return 500001;

        }
    }
    if(indeks == con.size())
    {
        int odp = 0;
        for(int i = 0; i < con.size(); i++)
        {
            if(con[i])
                odp += invest[i+1].second - invest[i].second;
        }
        return odp;
    }
    int res = 500002;
    res = min(rekur(invest,con,indeks+1),res);
    con[indeks] = 0;
    res = min(rekur(invest,con,indeks+1),res);
    return res;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin>>n;
    long long bilans = 0;
    int tmp;
    vector<pair<int,int>> invest;
    for(int i = 0; i < n; i++)
    {
        cin>>tmp;
        if(tmp != 0)
        {
            bilans += tmp;
            invest.push_back({tmp,i});
        }
    }
    if(bilans < 0)
    {
        cout<<-1<<endl;
    }
    else
    {
        vector<bool> con(invest.size()-1,1);
        cout<<rekur(invest,con,0)<<endl;
    }

}