#include <bits/stdc++.h>
using namespace std;
struct nd {
  int dist;
  int key, left, right;
};
nd nd[10005];
int stk[10005], q[10005];
int n, cl, i;
int merge(int a, int b) {
  if (a == 0 || b != 0 && nd[a].key < nd[b].key) {
    swap(a, b);
  }
  if (b == 0) return a;
  nd[a].right = merge(nd[a].right, b);
  if (nd[nd[a].left].dist < nd[nd[a].right].dist) {
    swap(nd[a].left, nd[a].right);
  }
  nd[a].dist = nd[nd[a].right].dist + 1;
  return a;
}
void solve() {
  int i, j;
  long long tot = 0;
  for (int i = 1; i <= cl; ++i)
    for (int j = q[i - 1] + 1; j <= q[i]; ++j)
      tot += abs(nd[j].key - nd[stk[i]].key);
  cout << tot << endl;
}
int main() {
  while (scanf("%d", &n) == 1) {
    memset(nd, 0, sizeof nd);
    q[0] = 0;
    cl = 0;
    for (int i = 1; i <= n; ++i) {
      scanf("%d", &nd[i].key);
      ++cl;
      stk[cl] = i;
      q[cl] = i;
      while (cl > 1 && nd[stk[cl]].key < nd[stk[cl - 1]].key) {
        --cl;
        stk[cl] = merge(stk[cl], stk[cl + 1]);
        if ((q[cl + 1] - q[cl]) % 2 == 1 && (q[cl] - q[cl - 1]) % 2 == 1) {
          stk[cl] = merge(nd[stk[cl]].left, nd[stk[cl]].right);
        }
        q[cl] = q[cl + 1];
      }
    }
    solve();
  }
  return 0;
}
