#include <bits/stdc++.h>
typedef int_fast64_t lli;
using namespace std;
signed main()
{
    ios_base::sync_with_stdio(NULL);
    cin.tie(nullptr);
    cout.tie(nullptr);
    lli n;
    cin >> n;
    vector<pair<lli, lli> > a;
    lli ai = 0, numb = 0;
    for(lli i = 0, x; i < n; i++)
    {
        cin >> x;
        if(a.empty() || !a.empty() && a[a.size()-1].first != x) a.emplace_back(x, 1);
        else if(!a.empty() && a[a.size()-1].first == x) a[a.size()-1].second++;
    }
    //for(auto& x : a) cout << x.first << " " << x.second << endl;
    lli d = 0, ans = 0;
    //cout << endl;
    for(lli i = a.size()-1; i >= 0; i--)
    {
        if(a[i].first - d > 0) ans += a[i].second*(a[i].first-d), d += a[i].second;
        else break;
    }
    cout << ans << endl;
}
