#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int ans, temp;
  int n, val, c;
  cin >> n;
  multiset<pair<int, int> > s;
  multiset<pair<int, int> >::iterator it;
  ans = 0;
  for (int i = 1; i <= n; i++) {
    cin >> val;
    if (s.size()) {
      it = s.begin();
      temp = (*it).first;
      c = (*it).second;
      if (temp < val) {
        if (c) {
          ans -= temp;
          ans += val;
          s.erase(it);
          s.insert(make_pair(val, 1));
          s.insert(make_pair(temp, 0));
        } else {
          ans -= temp;
          ans += val;
          s.erase(it);
          s.insert(make_pair(val, 1));
        }
      } else
        s.insert(make_pair(val, 0));
    } else
      s.insert(make_pair(val, 0));
  }
  cout << ans;
  return 0;
}
