n = int(input())
num_list = list(map(int, input().split()))
a = 0
x = 0
y = 1
b = num_list[x]
c = num_list[y]
for _ in num_list:
    d = c - b
    if d < 0:
        a += abs(d)
    x += 1
    y += 1
    b = num_list[x]
    c = num_list[y]
    b += abs(d)
    if y == n - 1:
        break
if a == 0:
    print(a)
else:
    print(a - 1)
