#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long re = 0, k = 1;
  char ch = getchar();
  while (ch > '9' || ch < '0') {
    if (ch == '-') k = -1;
    ch = getchar();
  }
  while (ch <= '9' && ch >= '0') {
    re = re * 10 + ch - 48;
    ch = getchar();
  }
  return re * k;
}
inline void write(long long x) {
  if (x < 0) return putchar('-'), write(-x), void();
  if (x < 10) return putchar(x + '0'), void();
  return write(x / 10), putchar(x % 10 + '0'), void();
}
long long a[300005], n, k, b[300005];
struct ss {
  long long val, cnt;
  bool operator>(const ss ot) const {
    if (val != ot.val) return val > ot.val;
    return cnt > ot.cnt;
  }
  ss(long long A = 0, long long B = 0) : val(A), cnt(B) {}
};
priority_queue<ss, vector<ss>, greater<ss> > q;
ss dp(long long mid) {
  long long ans = 0, lim = 0;
  for (register long long i = 1; i <= n; i++) {
    q.push(ss(a[i], i));
    ss t = q.top();
    if (t.val + b[i] <= 0) {
      ans += t.val + b[i];
      q.pop();
      q.push(ss(-b[i], i));
    }
  }
  while (!q.empty()) {
    ss t = q.top();
    lim += t.cnt;
    q.pop();
  }
  return ss(ans, lim);
}
signed main() {
  n = read();
  for (register long long i = 1; i <= n; i++) a[i] = read();
  for (register long long j = 1; j <= n; j++) b[j] = -a[j];
  ss t = dp(0);
  write(-t.val);
}
