#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  char ch = getchar();
  if (!(~ch)) return 0;
  int f = 1;
  while (ch > '9' || ch < '0') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  long long x = 0;
  while (ch >= '0' && ch <= '9') {
    x = (x << 3) + (x << 1) + (ch ^ 48);
    ch = getchar();
  }
  return x * f;
}
multiset<pair<long long, int> > s;
int main() {
  int n = read();
  long long sum = 0;
  for (register int i = 1; i <= n; ++i) {
    long long x = read();
    if (s.empty())
      s.insert(make_pair(x, 1));
    else if ((s.begin()->first) < x) {
      sum += x - (s.begin()->first);
      pair<long long, int> tmp = *s.begin();
      s.erase(s.begin());
      if (!tmp.second) s.insert(make_pair(tmp.first, 1));
      s.insert(make_pair(x, 0));
    } else
      s.insert(make_pair(x, 1));
  }
  printf("%lld\n", sum);
  return 0;
}
