#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct box
{
    ll n;
    ll a;
};
int main()
{
    ll n,c = 0,a,t;
    box x;
    vector < box > q;
    cin >> n;
    cin >> a;
    x.n = 1;
    x.a = a;
    for(ll i = 1; i < n; i++)
    {
        cin >> a;
        if(a == x.a)
        {
            x.n++;
        }
        else
        {
            q.push_back(x);
            x.n = 1;
            x.a = a;
        }
    }
    q.push_back(x);
    n = q.size();
    ll i = n - 1;
    t = 0;
    while(i > -1 && q[i].a > t)
    {
        c += q[i].n * (q[i].a - t);
        t += q[i].n;
        i--;
    }
    cout << c << endl;
    return 0;
}

