#include <bits/stdc++.h>
using namespace std;
long long n, x, ans, f[1000000], d;
void putit(long long x) {
  f[++d] = x;
  long long kk = d;
  while (kk != 1 && f[kk / 2] > f[kk]) swap(f[kk], f[kk / 2]), kk /= 2;
}
void outit() {
  f[1] = f[d--];
  long long x = 0, y = 1;
  while (x != y) {
    x = y;
    if (x * 2 <= d && f[x * 2] < f[y]) y = x * 2;
    if (x * 2 + 1 <= d && f[x * 2 + 1] < f[y]) y = x * 2 + 1;
    swap(f[y], f[x]);
  }
}
signed main() {
  ios::sync_with_stdio(false);
  cin >> n;
  f[++d] = 1e9;
  for (long long i = 1; i <= n; i++) {
    cin >> x;
    if (f[1] > x)
      putit(x);
    else {
      ans += x - f[1];
      outit();
      putit(x);
      putit(x);
    }
  }
  cout << ans << endl;
}
