#include <bits/stdc++.h>
const int maxn = 3e5 + 5;
const long long inf = 1e17 + 7;
template <typename T>
inline T max(const T &a, const T &b) {
  return a > b ? a : b;
}
template <typename T1, typename T2>
struct pair {
  T1 ft;
  T2 sd;
  pair() : ft(), sd() {}
  pair(T1 _ft, T2 _sd) : ft(_ft), sd(_sd) {}
  bool operator<(const pair &_Tp) const {
    if (sd != _Tp.sd) return sd < _Tp.sd;
    return ft < _Tp.ft;
  }
  bool operator>(const pair &_Tp) const {
    if (sd != _Tp.sd) return sd > _Tp.sd;
    return ft > _Tp.ft;
  }
};
int n;
long long p[maxn];
int status[maxn];
std::priority_queue<pair<int, long long>, std::vector<pair<int, long long> >,
                    std::greater<pair<int, long long> > >
    In, Out;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%lld", &p[i]);
  for (int i = 1; i <= n; i++) {
    long long alpha = In.empty() ? -inf : p[i] - In.top().sd;
    long long beta = Out.empty() ? -inf : p[i] - Out.top().sd;
    if (max(alpha, beta) > 0) {
      if (alpha > beta) {
        status[i] = 1, Out.push(pair<int, long long>(i, p[i]));
        status[In.top().ft] = -1;
        In.pop();
      } else {
        status[Out.top().ft] = 0, In.push(Out.top());
        Out.pop();
        status[i] = 1, Out.push(pair<int, long long>(i, p[i]));
      }
    } else
      In.push(pair<int, long long>(i, p[i]));
  }
  long long answer = 0;
  for (int i = 1; i <= n; i++) answer += status[i] * p[i];
  printf("%lld\n", answer);
  return 0;
}
