#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <fstream>
#include<stdlib.h>
#define rep( i, l, r ) for (int i = l; i <= r; i++)
#define down( i, l, r ) for (int i = l; i >= r; i--)
using namespace std;
const int DS = 1000000;
const int MaxInt = 1073741823;
int ans, n, num[DS], h[DS], l[DS], r[DS];
void LRotato(int w)
{
int o = h[w];
if (l[h[o]] == o) l[h[o]] = w; else r[h[o]] = w; h[w] = h[o];
r[o] = l[w]; h[l[w]] = o;
h[o] = w; l[w] = o;
}
void RRotato(int w)
{
int o = h[w];
if (l[h[o]] == o) l[h[o]] = w; else r[h[o]] = w; h[w] = h[o];
l[o] = r[w]; h[r[w]] = o;
h[o] = w; r[w] = o;
}
void Splay(int w)
{
while (h[w] != 0)
{
if (l[h[w]] == w) RRotato(w); else LRotato(w);
}
}
int Pre()
{
int p = l[l[0]];
while (r[p] != 0) p = r[p];
return p;
}
int Suf()
{
int p = r[l[0]];
while (l[p] != 0) p = l[p];
return p;
}
int Insert(int w)
{
int p = l[0], c = 0;
bool b = false;
while (p != 0)
{
if (num[w] <= num[p])
{
c = p; p = l[p]; b = true;
}
else
{
c = p; p = r[p]; b = false;
}
}
h[w] = c; if (b) l[c] = w; else r[c] = w;
Splay(w);
return min(num[w] - num[Pre()], num[Suf()] - num[w]);
}
int main()
{
scanf("%d", &n);
rep(i, 1, n) scanf("%d", &num[i]);
num[n+1] = -MaxInt; num[n+2] = MaxInt; num[0] = 0;
l[0] = n+1; r[n+1] = n+2; h[n+2] = n+1;
ans = Insert(1); ans = num[1];
rep(i, 2, n)
ans += Insert(i);
printf("%d\n", ans);
return 0;
}
I2luY2x1ZGUgPGNzdGRpbz4KI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3N0cmluZz4KI2luY2x1ZGUgPGNtYXRoPgojaW5jbHVkZSA8YWxnb3JpdGhtPgojaW5jbHVkZSA8ZnN0cmVhbT4KI2luY2x1ZGU8c3RkbGliLmg+CgojZ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