#include <bits/stdc++.h>
using namespace std;
long long n, x, ans = 0, s;
priority_queue<long long, vector<long long>, greater<long long> > q;
template <typename T>
inline void read(T &n) {
  T w = 1;
  n = 0;
  char ch = getchar();
  while (!isdigit(ch) && ch != EOF) {
    if (ch == '-') w = -1;
    ch = getchar();
  }
  while (isdigit(ch) && ch != EOF) {
    n = (n << 3) + (n << 1) + (ch & 15);
    ch = getchar();
  }
  n *= w;
}
template <typename T>
inline void write(T x) {
  char F[10001];
  if (x == 0) putchar('0');
  T tmp = x > 0 ? x : -x;
  if (x < 0) putchar('-');
  long long cnt = 0;
  while (tmp > 0) {
    F[cnt++] = tmp % 10 + 48;
    tmp /= 10;
  }
  while (cnt > 0) putchar(F[--cnt]);
}
int main() {
  long long i, j;
  read(n);
  for (i = 1; i <= n; i++) {
    read(x);
    if (!q.empty()) {
      s = q.top();
      if (s < x) {
        ans += x - s;
        q.pop();
        q.push(x);
      }
    }
    q.push(x);
  }
  write(ans);
  return 0;
}
