#include <bits/stdc++.h>
using namespace std;
const long long N = 666666;
long long n, arr[N];
multiset<long long> s;
signed main() {
  cin >> n;
  long long ans = 0;
  for (long long i = 1; i <= n; i++) cin >> arr[i];
  for (long long i = 1; i <= n; i++) {
    if (s.size() && (*s.begin()) < arr[i]) {
      ans += (arr[i] - *s.begin());
      s.erase(s.find((*s.begin())));
      s.insert(arr[i]);
    }
    s.insert(arr[i]);
  }
  cout << ans;
  return 0;
}
