// task name is zeroing

#include <bits/stdc++.h>

#define ONLINE

using namespace std;

const int N = 2e5 + 5;

long long a[N];
int t[4 * N];

void tree_build(int v, int l, int r)
{
    if (l == r - 1) return void(t[v] = l);

    int m = (l + r) / 2;
    tree_build(2 * v, l, m);
    tree_build(2 * v + 1, m, r);
    t[v] = a[t[2 * v]] > a[t[2 * v + 1]] ? t[2 * v + 1] : t[2 * v];
}

int tree_get(int v, int l, int r, int ll, int rr)
{
    if (r <= ll || rr <= l) return -1;
    if (ll <= l && r <= rr) return t[v];

    int m = (l + r) / 2;
    int p1 = tree_get(2 * v, l, m, ll, rr),
        p2 = tree_get(2 * v + 1, m, r, ll, rr);

    if (p1 == -1) return p2;
    if (p2 == -1) return p1;
    return a[p2] > a[p1] ? p1 : p2;
}

long long get_ans_solve1(int n, int l, int r, long long dt)
{
    if (r <= l) return 0;
    int p = tree_get(1, 0, n, l, r);

    long long ans = a[p] - dt;
    ans += get_ans_solve1(n, l, p, a[p]);
    ans += get_ans_solve1(n, p + 1, r, a[p]);

    return ans;
}

long long solve1(int n)
{
    tree_build(1, 0, n);
    return get_ans_solve1(n, 0, n, 0);
}

int main()
{
    #ifdef ONLINE
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    #endif // ONLINE

    int n;
    cin >> n;
    for (int i = 0; i < n; i++) cin >> a[i];
    a[n] = 5e18;
    long long ans = solve1(n);
    cout << ans;

    return 0;
}
