#include "bits/stdc++.h"
#define DIM 100007
#define mod 100000007
#define eps 0.000000001
#define pi 3.14
#define INF 100000000000001
#define fi first
#define se second

using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<long long, long long> pll;


ll t, n, a[DIM], b, c, res, k;

int main() {
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i ++){
        cin >> a[i];
    }
    c = 0;
    res = 0;
    for(int i = n; i >= 1; i --){
        k = 1;
        int j = i - 1;
        while(a[i] == a[j]){
            k ++;
            j --;
        }
        res += k * (max((ll)0, a[i] - c));
        c += k;
        i = j + 1;
       // cout << i << ' ' << c << ' ' << k << ' ' << j << ' ' << res << endl;
    }
    cout << res << endl;
}
