#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;
int n, p[N];
long long as;
priority_queue<long long> Q;
inline int read() {
  register char ch = getchar();
  register int x = 0;
  register bool y = 1;
  while (ch != '-' && (ch > '9' || ch < '0')) ch = getchar();
  if (ch == '-') ch = getchar(), y = 0;
  while (ch >= '0' && ch <= '9')
    x = (x << 1) + (x << 3) + (ch ^ '0'), ch = getchar();
  return y ? x : -x;
}
int main() {
  n = read();
  Q.push(-read());
  for (register int i = 2; i <= n; ++i) {
    int x = read();
    if (x <= -Q.top())
      Q.push(-x);
    else
      as += x + Q.top(), Q.pop(), Q.push(-x), Q.push(-x);
  }
  printf("%lld\n", as);
  return 0;
}
