#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

typedef long long ll;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("inA.txt", "r", stdin);

    ll n;
    cin >> n;
    vector<ll> a(n);
    for (auto &i : a)
        cin >> i;

    vector<pair<ll, ll>> b = {{a[0], 1}};
    for (int i = 1; i < n; i++) {
        if (a[i] == a[i-1])
            b[b.size() - 1].second++;
        else {
            b.push_back({a[i], 1});
        }
    }

    ll res = 0, add = 0;
    for (int i = b.size()-1; i >= 0; i--) {
        if (b[i].first - add > 0) {
            res += (b[i].first - add) * b[i].second;
            add += b[i].second;
        }
    }
    cout << res;

    return 0;
}