#include <bits/stdc++.h>
using namespace std;
const int N = 3e5;
long long a[N + 7];
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  multiset<pair<long long, bool> > ms;
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    if (ms.size() == 0) {
      ms.insert({a[i], false});
      continue;
    }
    long long minv = (*ms.begin()).first;
    bool minb = (*ms.begin()).second;
    if (a[i] <= minv) {
      ms.insert({a[i], false});
    } else {
      ans += a[i] - minv;
      ms.erase(ms.find({minv, minb}));
      if (minb == true) {
        ms.insert({minv, false});
      }
      ms.insert({a[i], true});
    }
  }
  cout << ans << endl;
  return 0;
}
