#include <bits/stdc++.h>
using namespace std;
const long long N = 3e5 + 5;
long long n, p[N], ret;
priority_queue<long long, vector<long long>, greater<long long> > Q;
signed main() {
  scanf("%lld", &n);
  for (long long i = 1; i <= n; i++) scanf("%lld", p + i);
  for (long long i = 1; i <= n; i++) {
    if (!Q.empty() && Q.top() < p[i])
      ret += p[i] - Q.top(), Q.pop(), Q.push(p[i]);
    Q.push(p[i]);
  }
  printf("%lld", ret);
  return 0;
}
