#include <bits/stdc++.h>
using namespace std;
long long n, p[300001], ans;
priority_queue<long long> q;
signed main() {
  scanf("%lld", &n);
  for (register long long i = 1; i <= n; ++i) scanf("%lld", &p[i]);
  for (register long long i = 1; i <= n; ++i) {
    if (!q.empty() && q.top() + p[i] >= 0) {
      ans += q.top() + p[i];
      q.pop();
      q.push(-p[i]);
    }
    q.push(-p[i]);
  }
  printf("%lld\n", ans);
  return 0;
}
