# coding: utf-8 # Your code here! N=int(input()) B=list(map(int,input().split())) empty=[] rem=[] ans=0 for i in range(len(B)): if B[i]==0: if len(rem)==0: empty.append(i) else: ans+=(i-rem.pop(-1)) else: while B[i]>1 and empty: ans+=(i-empty.pop(-1)) B[i]-=1 for j in range(B[i]-1): rem.append(i) print(ans)