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