#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
void solve() {
  long long i, j, k, l, r, m, n, a, b, c, d, x, y, z, t;
  cin >> n;
  long long ans = 0;
  multiset<long long> sold, intec;
  for (i = 0; i < n; i++) {
    cin >> x;
    if (sold.size() + intec.size() == 0) {
      intec.insert(x);
    } else {
      a = 10000000000;
      b = 10000000000;
      if (sold.size()) {
        a = *sold.begin();
      }
      if (intec.size()) {
        b = *intec.begin();
      }
      if (b < a && x > b) {
        ans -= b;
        ans += x;
        intec.erase(intec.begin());
        sold.insert(x);
      } else if (x > a) {
        ans -= a;
        ans += x;
        sold.erase(sold.begin());
        sold.insert(x);
        intec.insert(a);
      } else {
        intec.insert(x);
      }
    }
  }
  cout << ans << endl;
}
int32_t main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long t = 1;
  while (t--) solve();
  return 0;
}
