#include using namespace std; typedef long long ll; const double PI = acos(-1); const ll MOD = 1000000007; int main() { int N; cin >> N; vector B(N); for (int i = 0; i < N; i++) cin >> B[i]; queue que; stack s; ll count = 0; for (int i = 0; i < N; i++) { if (B[i] == 0 && s.empty()) que.push(i); else if (B[i] > 1 && que.empty()) { for (int j = 0; j < B[i]-1; j++) s.push(i); } else if (B[i] == 0) { int j = s.top(); s.pop(); count += (i - j); } else { while (!que.empty() && B[i] > 1) { int j = que.front(); que.pop(); count += (i-j); B[i]--; } if (B[i] > 1) { for (int j = 0; j < B[i]-1; j++) s.push(i); } } } cout << count << endl; }