#include <bits/stdc++.h>
#define ll long long
#define uns unsigned
using namespace std;
typedef set <int> :: iterator iter;
int n, x;
ll ans;
set <int> s;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &x);
if (s.empty()) {
ans += x;
s.insert(x);
continue;
}
iter pos = lower_bound(s.begin(), s.end(), x);
if (*pos == x)
continue;
else {
iter tmpit = pos;
tmpit--;
ans += min(abs(*tmpit - x), abs(*pos - x));
s.insert(x);
}
}
printf("%d", ans);
return 0;
}
谢dalao指教