#include <iostream>
#include <set>
using namespace std;
set<int> q;
int ans;
int n;
int main() {
cin >> n;
--n;
q.insert(-(1 << 31));
int t ;
cin >> t;
q.insert(t);
ans += t;
while (n--) {
cin >> t;
auto i = q.lower_bound(t);
int tmp = abs(*i - t);
--i;
if(*i != -(1 << 31)) {
tmp = min(tmp, abs(*i - t));
}
q.insert(t);
ans += tmp;
}
cout << ans;
return 0;
}