#include <bits/stdc++.h>

using namespace std;
int a[200002],n,counter;

bool checker(int &k)
{
    for (int i=k;i<n;i++) if (a[i]>0) {
        k=i;
        return false;
    }
    return true;
}
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    int k=0;
    bool zak=false;
    cin >> n;
    for (int i=0;i<n;i++)
        cin >> a[i];
    int i=0,maxim,start,low;
    while (!checker(k))
    {

        if (zak) start=k;
        else start=i;
        i=start+1;
        while (i<n && a[i]>=a[i-1]) i++;
        maxim=a[i-1];
        while (i<n && a[i]<=a[i-1]) i++;
        if (i==n)
            zak=true;
        i--;
        low=max(a[start],a[i]);
        if (start==0 && i==n-1)
        {
            counter+=maxim;
            for (int h=0;h<n;h++) a[h]=0;
            goto NEXT;
        }
        if (start==0 && maxim==a[0])
        {
            counter+=maxim-a[i];
            for (int h=0;h<i;h++) a[h]=a[i];
            goto NEXT;
        }
        if (i==n-1 && maxim==a[n-1])
        {
            counter+=maxim-a[start];
            for (int h=start;h<n;h++) a[h]=a[start];
            goto NEXT;
        }

        for (int h=start;h<=i;h++) if (a[h]>low) a[h]=low;
        counter+=maxim-low;
        if (low==maxim)
        {
            counter+=low;
            for (int h=start;h<=i;h++) a[h]=0;
        }
        NEXT:;
    }
    cout << counter;
    return 0;
}
