#include <bits/stdc++.h>

using namespace std;
long long a[100020];
long long n;
long long mn;
int main()
{
    //ios_base::sync_with_stdio(false);
    cin >> n;
    mn = 10000000000;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
        mn = min(a[i], mn);
    }
    long long res = 0;
    res += mn;
    long long r = 0;
    long long pred = -1;
    for (int i = 0; i < n; i++)
    {
        if (a[i] == mn)
        {
            if (pred != -1)
            {
                res += r - mn;
                //cout << res << endl;
                pred = -1;
                r = 0;
            }
        }
        else
        {
            if (pred == -1)
            {
                r = a[i];
                pred = a[i];
            }
            else
            {
                if (a[i] > pred)
                {
                    res += a[i] - pred;
                    //cout << res  << ' ' << a[i] << ' ' << pred << endl;
                    pred = a[i];
                }
                else
                {
                if (a[i] < pred)
                {
                    if (a[i] > r)
                    {
                        res += a[i] - r;
                        //cout << res << endl;
                        pred = a[i];
                    }
                    else
                    {
                    if (a[i] < r)
                    {
                        res += r - a[i];
                        //cout << res << endl;
                        r = a[i];
                        pred = a[i];
                    }
                    }
                }
                }
            }
        }
    }
    if (pred != -1)
    {
        res += r - mn;
        //cout << res << endl;
    }
    cout << res;
    return 0;
}
