n = int(input()) b = list(map(int, input().split())) have = [] ans = 0 r = 0 for i in range(n): if b[i] > 1: have.append((i, b[i])) if b[i] == 0: if have != []: g, p = have.pop() b[i] += 1 b[g] -= 1 ans += i-g if p-1 > 1: have.append((g, p-1)) else: if b[r] > 1: g = r else: for g in range(i, n): if b[g] > 1: r = g break b[i] += 1 b[g] -= 1 ans += g-i print(ans)