#include using namespace std::literals::string_literals; using i64 = std::int_fast64_t; using std::cout; using std::cerr; using std::endl; using std::cin; template std::vector make_v(size_t a){return std::vector(a);} template auto make_v(size_t a,Ts... ts){ return std::vector(ts...))>(a,make_v(ts...)); } int main() { int n; scanf("%d", &n); std::vector b(n); for(int i = 0; i < n; i++) scanf("%d", &b[i]); i64 ans = 0; std::stack L, R; for(int i = 0; i < n; i++) { if(b[i] == 1) continue; if(b[i]) { while(!L.empty() and b[i] > 1) { ans += (i - L.top()); L.pop(); b[i]--; } while(b[i]-- > 1) R.push(i); } else { if(R.empty()) L.push(i); else { ans += (i - R.top()); R.pop(); } } } printf("%lld\n", ans); return 0; }