#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  char c = getchar();
  long long x = 0;
  bool f = 0;
  for (; !isdigit(c); c = getchar()) f ^= !(c ^ 45);
  for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
  if (f) x = -x;
  return x;
}
const long long M = 3e5 + 10;
long long n, a[M], ans;
priority_queue<long long> q;
signed main() {
  n = read();
  for (long long i = 1; i <= n; i++) a[i] = read();
  for (long long i = 1; i <= n; i++) {
    if (!q.empty() && -q.top() < a[i])
      ans += a[i] + q.top(), q.push(-a[i]), q.pop();
    q.push(-a[i]);
  }
  cout << ans << endl;
  return 0;
}
