#include <bits/stdc++.h>
long long n, m, heap[1010000], tail, ans;
char mark[110000];
void swap(long long x, long long y) {
  long long tmp = heap[x];
  heap[x] = heap[y];
  heap[y] = tmp;
}
long long cmp(long long x, long long y) { return heap[x] <= heap[y]; }
void up(long long x) {
  while ((x >> 1) >= 1) {
    if (x == 1 || cmp(x >> 1, x))
      return;
    else
      swap(x, x >> 1);
    x >>= 1;
  }
}
void down(long long x) {
  while ((x << 1) <= tail) {
    long long y = x << 1;
    if (y < tail && cmp(y + 1, y)) y++;
    if (cmp(x, y))
      return;
    else
      swap(x, y);
    x = y;
  }
}
signed main() {
  long long n, x;
  scanf("%lld%lld", &n, &x), heap[++tail] = x, up(tail);
  for (long long i = 1, x; i < n; i++) {
    scanf("%lld", &x);
    if (tail && heap[1] < x) ans += x - heap[1], heap[1] = x, down(1);
    heap[++tail] = x, up(tail);
  }
  printf("%lld", ans);
  return 0;
}
