#include <bits/stdc++.h>
#define ll long long
#define ff first
#define pb push_back
#define ss second
#define endl '\n'
#define y1 y6
#define j1 j6
#define rr return 0;
using namespace std;
ll n,i,o,d,m,j,x,y;
const ll INF=1e9;
ll a[1000007];
ll dp[1000007];
ll c[1000007];
int main()
{
//    freopen("loganqueries.in","r",stdin);
//    freopen("loganqueries.out","w",stdout);
//    ios_base::sync_with_stdio(false);
//    cin.tie(0);
//    cout.tie(0);
    cin>>n;
    ll A[n];
    for(i=0;i<n;i++){
        cin>>A[i];
    }
    ll ans=0;
    ll k=0;
    ll x=A[n-1];
    ll q=0;
    for(i=n-1;i>=0;i--)
    {
        if(A[i]!=x) {k+=q; q=0; x=A[i];}
        if(A[i]-k<=0) {cout<<ans; return 0;}
        else {ans+=A[i]-k;}
        q++;
    }
    cout<<ans;
    return 0;
}
