#include <iostream>

int main()
{
    int n;
    scanf("%d", &n);
    long long a[n];
    for (int i = 0; i < n; i++) scanf("%lld", &a[i]);
    long long res = 0;
    int p = n - 1;
    long long d = 0;
    while (p >= 0 && a[p] > d)
    {
        long long dd = 0;
        while (p > 0 && a[p] == a[p - 1])
        {
            dd++;
            p--;
        }
        dd++;
        res += dd * (a[p] - d);
        p--;
        d += dd;
    }
    printf("%lld", res);
    return 0;
}
