#include <bits/stdc++.h>
using namespace std;
const long long INF = 3e5 + 5;
long long n, heap[INF], tot, ans;
void heap_push(long long x) {
  heap[++tot] = x;
  long long xx = tot;
  while (xx > 1) {
    long long k = (xx >> 1);
    if (heap[k] > heap[xx])
      swap(heap[k], heap[xx]);
    else
      break;
    xx = k;
  }
  return;
}
void heap_down(long long x) {
  long long xx = x;
  while ((xx << 1) <= tot) {
    long long k = (xx << 1);
    if (k + 1 <= tot && heap[k + 1] < heap[k]) k++;
    if (heap[k] < heap[xx])
      swap(heap[k], heap[xx]);
    else
      break;
    xx = k;
  }
  return;
}
void del(long long x) {
  heap[x] = heap[tot];
  tot--;
  heap_down(x);
  return;
}
signed main() {
  scanf("%lld", &n);
  for (long long i = 1; i <= n; i++) {
    long long x = 0;
    scanf("%lld", &x);
    if (tot && heap[1] < x) {
      ans += x - heap[1];
      del(1);
      heap_push(x);
    }
    heap_push(x);
  }
  cout << ans << "\n";
  return 0;
}
