#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#define int long long
std::vector <int> tree;
int n;
int x;
int minn = 1e9, maxx = -1e9;
int ans;
signed main(){
std::cin >> n;
std::cin >> x;
tree.push_back(x);
ans += x;
for(int i = 2; i <= n; ++i){
std::cin >> x;
minn = *--std::lower_bound(tree.begin(), tree.end(), x);
maxx = *std::upper_bound(tree.begin(), tree.end(), x);
ans += std::min(abs(x - minn), abs(maxx - x));
tree.insert(std::lower_bound(tree.begin(), tree.end(), x), x);
}
std::cout << ans << '\n';
return 0;
}