#include <bits/stdc++.h>

using namespace std;

using ll = long long;

int n;
vector<int> a;
vector< pair<int,int> > b;

int main ()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> n;

    a.resize(n);

    for ( auto& el : a )
        cin >> el;

    b.push_back({ a[0], 1 });

    for ( int i=1; i<n; i++ )
    {
        if ( a[i-1] == a[i] )
            b.back().second++;
        else
            b.push_back({ a[i], 1 });
    }

    ll ans = 0;
    ll cur = 0;

    for ( int i = int(b.size())-1; i>=0; i-- )
    {
        if ( b[i].first-cur <= 0 )
            break;

        ans += (b[i].first-cur)*1ll*b[i].second;
        cur += b[i].second;
    }

    cout << ans;

    return 0;
}
