#include <bits/stdc++.h>
using namespace std;
long long INF = 1E9;
long long M = 1E9 + 7;
inline long long power(long long a, long long p) {
  long long res = 1, x = a;
  while (p) {
    if (p & 1) res = (res * x);
    x = (x * x);
    p >>= 1;
  }
  return res;
}
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& p) {
  os << "[ ";
  for (T x : p) os << x << " ";
  os << "]" << endl;
  return os;
}
template <typename T>
ostream& operator<<(ostream& os, const set<T>& p) {
  os << "{ ";
  for (T x : p) os << x << " ";
  os << "}" << endl;
  return os;
}
template <typename Tk, typename Tv>
ostream& operator<<(ostream& os, const map<Tk, Tv>& p) {
  os << "{ ";
  for (pair<Tk, Tv> x : p) os << x << " ";
  os << "}" << endl;
  return os;
}
template <typename Tk, typename Tv>
ostream& operator<<(ostream& os, const pair<Tk, Tv>& p) {
  os << "{" << p.first << ',' << p.second << "}";
  return os;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  if (fopen("input.txt", "r")) {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
  }
  long long n;
  cin >> n;
  multiset<pair<int, int> > s;
  long long ans = 0, x;
  for (long long i = 0; i < n; i++) {
    cin >> x;
    if (s.empty())
      s.insert({x, 0});
    else if ((*s.begin()).first > x)
      s.insert({x, 0});
    else {
      pair<int, int> y = *s.begin();
      if (y.second) {
        ans -= y.first;
        ans += x;
        s.erase(s.begin());
        s.insert({y.first, 0});
        s.insert({x, 1});
      } else {
        ans -= y.first;
        ans += x;
        s.erase(s.begin());
        s.insert({x, 1});
      }
    }
  }
  cout << ans << "\n";
  return 0;
}
