#include <bits/stdc++.h>
using namespace std;
long long get() {
  long long x = 0, f = 1;
  char c = getchar();
  while (!isdigit(c)) {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (isdigit(c)) {
    x = x * 10 + c - '0';
    c = getchar();
  }
  return x * f;
}
long long n, ans = 0;
priority_queue<long long> q;
signed main() {
  n = get();
  for (long long i = 1; i <= n; i++) {
    long long a = get();
    if (q.size() && a > -q.top()) ans += a + q.top(), q.pop(), q.push(-a);
    q.push(-a);
  }
  printf("%lld\n", ans);
  return 0;
}
