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