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

bool czy = true;
int n;
long long a, dp[5007];

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

    cin >> n;
    for (int i=0; i<=5000; i++)
        dp[i] = -inf;
    cin >> a;
    dp[0] = a;
    for (int i=2; i<=n; i++)
    {
        cin >> a;
        for (int j=5000; j>=0; j--)
        {
            if (dp[j] >= 0)
            {
                dp[j+1] = max(dp[j+1], dp[j]);
                dp[j] = 0;
            }
            else if (dp[j] != -inf)
            {
                dp[j+1] = max(dp[j+1], dp[j]);
                dp[j] = -inf;
            }
        }
        for (int j=5000; j>=0; j--)
        {
            if (dp[j] != -inf)
                dp[j] += a;
        }
    }

    for (int i=0; i<=5000; i++)
    {
        if (dp[i] >= 0)
        {
            cout << i << "\n";
            return 0;
        }
    }
    cout << "-1" << "\n";

    return 0;
}