#include <bits/stdc++.h>
typedef long long ll;
#define endl '\n'
using namespace std;
const int N=2000100;
int a[N];
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n;cin>>n;
    for (int i=1;i<=n;i++) cin>>a[i];
    vector<pair<int,int> >v;
    int cnt=1;
    for (int i=2;i<=n;i++){
        if (a[i]==a[i-1]) cnt++;
        else {
            v.push_back({a[i-1],cnt});
            cnt=1;
        }
    }
    v.push_back({a[n],cnt});
    ll res=0ll;
    int sum=0;
    for (int i=(int)v.size()-1;i>=0;i--){
        res+=max(0,v[i].first-sum)*1ll*v[i].second;
        sum+=v[i].second;
    }

    cout<<res<<endl;
    return 0;
}
