#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n;
    cin >> n;
    vector <int> a(n);
    for (int i = 0; i < n; i++)
        cin >> a[i];
    int res = 0;
    int l = 0, r = n - 1;
    int are_on = 0;
    while (true)
    {
        if (r - l == -1)
            break;
        if (a[l] - are_on == 0)
        {
            l++;
        }
        else
        {
            res += a[r] - are_on ;
            for (int i = r - 1; i >= l; i--)
                if (a[i] == a[r])
                    a[i]++;
                else
                    break;
            r--;
            are_on += 1;
        }
    }
    cout << res;
}
