#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#pragma comment(linker, "/STACK:102400000,102400000")
#define ls i<<1
#define rs ls | 1
#define mid ((ll+rr)>>1)
typedef long long LL;
const LL INF = (1LL<<60)-1;
const double Pi = acos(-1.0);
const int N = 1e5+10, M = 1e6+11, mod = 1e9+7, inf = (1<<30)-1;
struct data {int l,r,v,size,rnd,w;}tr[N * 20];
int n,size=0,root,ans,Ans;
void update(int k) {tr[k].size=tr[tr[k].l].size+tr[tr[k].r].size+tr[k].w;}
void rturn (int &k){
int t=tr[k].l;tr[k].l=tr[t].r;tr[t].r=k;
tr[t].size=tr[k].size;update(k);k=t;
}
void lturn(int &k) {
int t=tr[k].r;tr[k].r=tr[t].l;tr[t].l=k;
tr[t].size=tr[k].size;update(k);k=t;
}
void insert(int &k,int x) {
if(k == 0) {
size++;k=size;
tr[k].size=tr[k].w=1;
tr[k].v=x;
tr[k].rnd=rand();
return ;
}
tr[k].size++;
if(tr[k].v == x) tr[k].w++;
else if(x > tr[k].v) {
insert(tr[k].r,x);
if(tr[tr[k].r].rnd<tr[k].rnd) lturn(k);
} else {
insert(tr[k].l,x);
if(tr[tr[k].l].rnd<tr[k].rnd) rturn(k);
}
}
void query_pre(int k,int x) {
if(k == 0) return ;
if(tr[k].v <= x) {
ans=tr[k].v;query_pre(tr[k].r,x);
} else query_pre(tr[k].l,x);
}
void query_nex(int k,int x) {
if(k == 0) return ;
if(tr[k].v >= x) {
ans=tr[k].v;;query_nex(tr[k].l,x);
} else query_nex(tr[k].r,x);
}
int main() {
root = 0;
scanf("%d",&n);
for(int i = 1; i <= n; ++i) {
int x;
scanf("%d",&x);
if(i == 1) {
Ans = x;
} else {
ans = -inf;query_pre(root,x);
int fi = ans;
ans = inf;query_nex(root,x);
int se = ans;
//cout<<fi<<" "<<se<<endl;
if(fi!=-inf || se != inf) Ans += min(x-fi,se-x);
}
insert(root,x);
}
printf("%d\n",Ans);
return 0;
}