#include <bits/stdc++.h>

using namespace std;

int main(){
    ios::sync_with_stdio();cin.tie();


    //XY0045

    int n,a[100000],s=0,p,pr,le,kpr,srav,i,ob,j;
    pair <int,int> b[100000];
    cin>>n;
    //cout<<"Andrey_pidor))"<<"\n";
    for (i=0;i<n;i++){
        cin>>a[i];
        b[i].first=a[i];
        b[i].second=i;
    }
    //cout<<"Andrey_pidor))"<<"\n";
    sort(b,b+n);

    a[n]=0;

    for (i=n-1;i>=0;i-=1){

        ob=b[i].second;
        //cout<<ob;
        if (ob==0){
            p=0;
            while (a[p+1]==a[0]){
                p++;
            }
            if (a[p+1]>a[0]){
                continue;
            }
            s+=a[0]-a[p+1];
            for (j=0;j<=p;j++){
                a[j]=a[p+1];
            }
        }else{
            if (ob==n-1){
                p=n-1;
                while(a[p-1]==a[n-1]){
                    p--;
                }
                if (a[p-1]>a[n-1]){
                    continue;
                                  }
                s+=a[n-1]-a[p-1];
                for (j=n-1;j>=p;j--){
                    a[j]=a[p-1];

                }
            }else{
            p=ob;
            while (a[p+1]==a[ob]){
                p++;
            }
            pr=a[p+1];
            kpr=p;
            p=ob;

            while(a[p-1]==a[ob]){
                p--;
            }
            le=a[p-1];

            srav=max(pr,le);
            if (srav>a[ob]){
                srav=min(pr,le);
            }
            if (srav>a[ob]){
                continue;
            }
            s+=a[ob]-srav;
            for (j=p;j<=kpr;j++){
                a[j]=srav;
            }
            }
        }
       // cout<<s<<"\n";


        if (a[0]==0){
            break;
        }
    }
    cout<<s;
    return 0;
}
