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

using namespace std;
int n;
const int N = 500009, INF = 1e9;
int nums[N], dp[N];

int solv()
{
    dp[1] = (nums[1] >= 0 ? 0 : INF);
    for(int i = 2; i <= n; i++) {
        long long curr_sum = 0;
        dp[i] = INF;
        for(int j = i; j >= 1; j--) {
            curr_sum += nums[j];
            if(curr_sum >= 0) {
                dp[i] = min(dp[i], dp[j - 1] + i - j);
            }
        }
    }
    return dp[n];
}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++) {
        cin >> nums[i];
    }
    int sol = solv();
    if(sol <= n)
        cout << sol;
    else
        cout << -1;


    return 0;
}