#include<cstdio>
#include<set>
#include<algorithm>
#define ittype multiset<int>::iterator
using namespace std;
multiset<int> A;
int main()
{
int sum=0,i,n,t;
scanf("%d",&n);
for (i=1;i<=n;i++)
{
if (scanf("%d",&t)==EOF) t=0;
ittype it=A.insert(t),i1,i2;
if (i==1) {sum=t;continue;}
int tmin=1E9;
i1=it,i2=it,i2++;
if (it!=A.begin()) {i1--;tmin=min(tmin,*it-*i1);}
if (i2!=A.end()) tmin=min(tmin,*i2-*it);
sum+=tmin;
}
printf("%d\n",sum);
}