n = int(input())
a = []
b = list(map(int, input().split()))
ind = -1
for i in range(len(b)):
    if i == 0 or b[i - 1] != b[i]:
        a.append([b[i], 1])
        ind += 1
    else:
        a[ind][1] += 1
a = a[::-1]
s = 0
c = 0
for i in range(len(a)):
    if a[i][0] + c <= 0:
        break
    s += (a[i][0] + c) * a[i][1]
    c -= a[i][1]
print(s)
    
