#include <bits/stdc++.h>
using namespace std;
const long long N = 3e5 + 5;
inline long long read() {
  long long x = 0, f = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = x * 10 + c - '0';
    c = getchar();
  }
  return x * f;
}
long long n, a[N];
priority_queue<long long, vector<long long>, greater<long long> > q;
signed main() {
  n = read();
  for (long long i = 1; i <= n; i++) a[i] = read();
  long long ans = 0;
  for (long long i = 1; i <= n; i++) {
    long long val = 0;
    if (q.size() && q.top() <= a[i]) {
      ans += (a[i] - q.top()), q.pop(), q.push(a[i]), q.push(a[i]);
    } else
      q.push(a[i]);
  }
  printf("%lld\n", ans);
  return 0;
}
