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