#include <bits/stdc++.h>

using namespace std;

struct ball {
    long long n;
    long long d;
};

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

	long long n, a, c, f, e;
    ball b;
    vector <ball> m;
	cin >> n;
    cin >> a;
    b.d = a;
    b.n = 1;
    for (int i = 1; i < n; i++) {
        cin >> a;
        if (a != b.d) {
            m.push_back(b);
            b.d = a;
            b.n = 1;
        } else {
            b.n++;
        }
    }
    m.push_back(b);
    e = 0;
    f = 0;
    for (int i = m.size() - 1; i > -1; i--) {
        if (m[i].d >= f) {
            e += (m[i].d - f) * m[i].n;
            f += m[i].n;;
        } else {
            break;
        }
    }
    cout << e;
    return 0;
}
