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
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int inf = 1e6 + 9;

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

    int n;
    ll global_sum = 0;
    cin >> n;
    vector<int> arr(n + 9, 0), dp(n + 9, 0);

    for (int i = 1; i <= n; i++)
        cin >> arr[i], global_sum += arr[i];

    if (global_sum < 0)
    {
        cout << -1 << endl;
        return 0;
    }

    for (int i = 1; i <= n; i++)
    {
        cin >> arr[i];

        if (arr[i] >= 0)
            dp[i] = dp[i - 1];
        else
            dp[i] = inf;
        ll sum = 0;
        for (int j = i; j >= 0; j--)
        {
            sum += arr[j];
            if (sum >= 0)
                dp[i] = min(dp[i], i - j + dp[j - 1]);
        }
    }
    if (dp[n] != inf)
        cout << dp[n] << endl;
    else
        cout << -1 << endl;
}