#include <iostream>
#include <set>
#include <map>
#include <math.h>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;
typedef long long ll;
const int VERYLONGINT = 1000000001;

struct tf {
    vector<int> tree;
    int size;
    tf(int n) {
        size = n + 1;
        tree.assign(n + 1, 0);
    }
    void add(int p, int v) {
        for (int i = p + 1; i < size; i += (i & (-i)))
            tree[i] += v;
    }

};

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    cin >> n;
    vector<ll> a(n);
    for (int i = 0; i < n; i++)
        cin >> a[i];
    ll cf = 0;
    vector<pair<ll, ll>> cn;
    int cnt = 1;
    for (int i = 1; i < n; i++)
        if (a[i - 1] != a[i]) {
            cn.push_back({ a[i - 1], cnt });
            cnt = 1;
        }
        else
            cnt++;
    cn.push_back({ a[n - 1], cnt });
    ll res = 0;
    for (int i = cn.size() - 1; i > -1; i--) {
        res += max(0ll, cn[i].first - cf) * cn[i].second;
        cf += cn[i].second;
    }
    cout << res << "\n";
    return 0;
}