#include <iostream>

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