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
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <unordered_map>
#include <queue>

using namespace std;

unordered_map<int, int> memo;
vector<long long> sums;

int best = 500001;

int findMin(const vector<int>& energies, int start, int sofar = 0){

  if(memo.find({start}) != memo.end()) {
      return memo[{start}];
  }
  long long sum = sums[energies.size()] - sums[start];

  if(start == energies.size() - 1){
    if(energies[start] >= 0){
      return 0;
    } else {
      return energies.size() - start;
    }
  }
  if(sum < 0){
    return 500001;
  }
  int ret = energies.size()- start;
  for(int i = start; i < energies.size(); i++){
    if(sums[i + 1] - sums[start] >= 0) {
      ret = min(ret, i - start + findMin(energies, i + 1, sofar + i - start));
      if((sofar + i - start) > best) break;
    }
  }
  best = min(best, ret + sofar);
  memo[{start}] = ret;
  return ret;
}

int main(){
  int n;
  cin >> n;

  vector<int> energy;
  long long sum = 0;
  for(int i = 0; i < n; i++){
    int tmp = 0;
    sums.push_back(sum);
    cin >> tmp;
    sum += tmp;
    energy.push_back(tmp);
  
  }
  sums.push_back(sum);
  if(sum < 0){
    cout << -1;
  } else {
    cout << findMin(energy, 0);
  }
  cout << endl;
}