#include <bits/stdc++.h>
using namespace std;
priority_queue<long long, vector<long long>, greater<long long> > pq;
int main() {
  int n;
  scanf("%d", &n);
  long long ans = 0;
  for (int i = 0; i < n; ++i) {
    long long p;
    scanf("%lld", &p);
    if (pq.empty()) {
      pq.push(p);
      continue;
    }
    long long tmp = pq.top();
    if (p <= tmp) {
      pq.push(p);
      continue;
    }
    ans += p - tmp;
    pq.pop();
    pq.push(p), pq.push(p);
  }
  printf("%lld\n", ans);
  return 0;
}
