#include <bits/stdc++.h>
using namespace std;
long long sum, n, x;
priority_queue<long long, vector<long long>, greater<long long> > q;
inline int read() {
  char ch = getchar();
  int f = 1, x = 0;
  while (ch > '9' || ch < '0') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = (x << 1) + (x << 3) + ch - '0';
    ch = getchar();
  }
  return x * f;
}
int main() {
  n = read();
  for (long long i = 1; i <= n; i++) {
    x = read();
    if (!q.empty() && x > q.top()) {
      sum += (x - q.top());
      q.pop();
      q.push(x);
      q.push(x);
    } else {
      q.push(x);
    }
  }
  printf("%lld", sum);
  return 0;
}
