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
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
	int n;
	std::cin >> n;
	std::vector<int> energy(n);
	long long total = 0;
	for (int i = 0; i < n; i++) {
		std::cin >> energy[i];
		total += energy[i];
	}

	if (total < 0) {
		std::cout << "-1\n";
		return 0;
	}


	std::vector<int> memo(n + 1, n);
	memo[0] = 0;
	for (int i = 0; i < n; i++) {
		if (energy[i] == 0) {
			memo[i + 1] = memo[i];
			continue;
		}
		long long sum = 0;
		for (int j = i; j >= 0; --j) {
			if (i - j >= memo[i + 1]) {
				break;
			}
			sum += energy[j];
			if (sum >= 0) {
				memo[i + 1] = std::min(memo[i + 1], memo[j] + i - j);
			}
		}
	}

	std::cout << memo[n] << '\n';
	return 0;
}