MOD = 10 ** 9 + 7 INF = 10 ** 10 import sys input = sys.stdin.readline sys.setrecursionlimit(100000000) dy = (-1,0,1,0) dx = (0,1,0,-1) from bisect import bisect_left,bisect_right from collections import deque def main(): n = int(input()) b = list(map(int,input().split())) ans = 0 idx1 = deque() idx2 = deque() for i in range(n): if b[i] == 1: continue elif b[i] == 0: if len(idx2) > 0: p = idx2.popleft() ans += i - p else: idx1.append(i) elif b[i] > 1: while len(idx1) and b[i] > 1: b[i] -= 1 p = idx1.popleft() ans += i - p for _ in range(b[i] - 1): idx2.append(i) print(ans) if __name__ =='__main__': main()