#include<bits/stdc++.h>
using namespace std;
const int N = 5e5+5;
int n,k,ans(0),rt,w(0);
struct node{
int lc,rc,fa,pos,vis;
#define lc(x) t[x].lc
#define rc(x) t[x].rc
#define fa(x) t[x].fa
#define pos(x) t[x].pos
#define vis(x) t[x].vis
}t[N];
void zig(int &x){ //右旋
int y=lc(x);
lc(x) = rc(y);
rc(y) = x;
x = y;
}
void zag(int &x){ //左旋
int y=rc(x);
rc(x) = lc(y);
lc(y) = x;
x = y;
}
void insert(int &x,const int vi){
if (!x){
vis(x=++w)=vi;
pos(x)=rand();
return ;
}
if (vi<vis(x)){
insert(lc(x),vi);
if (pos(lc(x))<pos(x))
zig(x);
}
else{
insert(lc(x),vi);
if (pos(lc(x))<pos(x))
zag(x);
}
}
int querypre(const int vi){
int x=rt,pr=-INT_MAX;
while(x){
if (vi>=vis(x)) pr=vis(x),x=rc(x);
else x=lc(x);
}
return pr;
}
int querysuf(const int vi){
int x=rt,sf=INT_MAX;
while(x){
if (vi<=vis(x)) sf=vis(x),x=lc(x);
else x=rc(x);
}
return sf;
}
int main(){
cin >> n >> k;
insert(rt,k);
ans+=k;
for (int i=2;i<=n;i++){
cin >> k;
int x=querypre(k);
int y=querysuf(k);
ans += min(k-x,y-k);
insert(rt,k);
}
cout << ans;
return 0;
}