#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  register long long x = 0, f = 0, ch = getchar();
  while ('0' > ch || ch > '9') f ^= ch == '-', ch = getchar();
  while ('0' <= ch && ch <= '9')
    x = (x << 1) + (x << 3) + (ch ^ '0'), ch = getchar();
  return f ? -x : x;
}
long long n, x, ans;
priority_queue<long long, vector<long long>, greater<long long> > q;
signed main() {
  n = read();
  for (register long long i = 1; i <= n; ++i) {
    x = read();
    if (q.size() && q.top() < x) {
      ans += x - q.top();
      q.pop();
      q.push(x);
    }
    q.push(x);
  }
  printf("%lld\n", ans);
  return 0;
}
