#include <iostream>
using namespace std;
struct tree
{
int l,r;
long long x;
}s[1000000];
int n;
int cnt=1;
long long maxn=1e15;
void insertion(long long key,int now)
{
maxn=min(maxn,abs(s[now].x-key));
if(key>s[now].x)
{
if(s[now].r==0)
{
s[now].r=cnt;
s[cnt].x=key;
return;
}
insertion(key,s[now].r);
}
else
{
if(s[now].l==0)
{
s[now].l=cnt;
s[cnt].x=key;
return;
}
insertion(key,s[now].l);
}
return;
}
int main()
{
ios::sync_with_stdio(false);
long long ans=0;
int i,j;
cin>>n;
int temp;
cin>>temp;
ans+=temp;
s[1].x=temp;
for(i=2; i<=n; i++)
{
cin>>temp;
maxn=1e15;
cnt++;
insertion(temp,1);
ans+=maxn;
}
cout<<ans;
return 0;
}