n = int(input())
a = [int(i) for i in input().split()]
l = 0
k = 0
dp = []
for i in range(len(a)):
    if i==0:
        dp.append([a[i]])
    elif a[i]==a[i-1]:
        dp[-1].append(a[i])
    else:
        dp.append([a[i]])
dp = dp[::-1]
for i in range(len(dp)):
    if i==0:
        l+=sum(dp[i])
        k+=len(dp[i])
    else:
        if k>dp[i][0]:
            k==len(dp[i])
        else:
            l+=len(dp[i])*(dp[i][0]-k)
            k+=len(dp[i])
    
            
print(l)