#include <bits/stdc++.h>
using namespace std;

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

	int n;
	cin >> n;

    vector<long> balls(n, 0);
    for (int c = 0; c < n; ++c) {
        std::cin >> balls[c];
    }

    unsigned long cost = 0;
    long shift = 0;

    for (long q = n - 1; q >= 0; --q) {
        long real_price = balls[q] - shift;
        if (real_price < 1) continue;

        long amount = 1;

        long w = q - 1;
        for (; w >= 0 && balls[w] == balls[q]; w--, amount++);
        q = w + 1;

        cost += real_price*amount;
        shift += amount;
    }

    cout << cost << '\n';

    return 0;
}
