#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
struct TREE {
int ch[2], p, v, siz, l, r;
}tr[N];
inline static int read() {
int x = 0, w = 1;
char ch = 0;
while (ch < '0' || ch > '9') {
if (ch == '-') w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + (ch - '0');
ch = getchar();
}
return x * w;
}
int n, m, root, idx;
void pushup(int u) { tr[u].siz = tr[tr[u].ch[0]].siz + tr[tr[u].ch[1]].siz + 1; }
void rotate(int u) {
int x = tr[u].p, y = tr[x].p;
int k = tr[x].ch[1] == u;
tr[y].ch[tr[y].ch[1] == x] = u, tr[u].p = y;
tr[x].ch[k] = tr[u].ch[k ^ 1], tr[tr[u].ch[k ^ 1]].p = x;
tr[x].p = u, tr[u].ch[k ^ 1] = x;
pushup(x), pushup(u);
}
void splay(int u, int k) {
while (tr[u].p != k) {
int x = tr[u].p, y = tr[x].p;
if (y != k) {
if ((tr[y].ch[1] == x) ^ (tr[x].ch[1] == x)) rotate(u);
else rotate(x);
}
rotate(u);
}
if (!k) root = u;
}
void insert(int v) {
int u = root, p = 0;
while (u) p = u, u = tr[u].ch[tr[u].v < v];
u = ++ idx;
if (p) tr[p].ch[tr[p].v < v] = u;
tr[u].p = p, tr[u].v = v, tr[u].siz = 1;
splay(u, 0);
}
int pr(int v) {
int u = root, res = 1e9;
while (u) {
if (tr[u].v <= v) res = tr[u].v, u = tr[u].ch[1];
else u = tr[u].ch[0];
}
return res;
}
int ne(int v) {
int u = root, res = 1e9;
while (u) {
if (tr[u].v >= v) res = tr[u].v, u = tr[u].ch[0];
else u = tr[u].ch[1];
}
return res;
}
int main() {
n = read();
int ans = 0;
for (int i = 1; i <= n; i ++ ) {
int s = read();
if (i != 1) ans += min(abs(s - pr(s)), abs(ne(s) - s));
else ans += s;
insert(s);
}
cout << ans;
return 0;
}