#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e6 + 10;
const int MOD = 1e9 + 7;
const double PI = acos(-1.0);
int link[MAX];
struct lenka {
  long long val, id;
  bool operator<(const lenka& q) const {
    if (val == q.val) return link[q.id] != 0;
    return q.val < val;
  }
};
priority_queue<lenka> p;
int main() {
  int n;
  scanf("%d", &n);
  while (!p.empty()) p.pop();
  for (int i = 1; i <= n; i++) link[i] = 0;
  long long ans = 0, t = 0;
  for (int i = 1; i <= n; i++) {
    long long x;
    scanf("%lld", &x);
    p.push({x, i});
    if (x <= p.top().val) continue;
    lenka now = p.top();
    p.pop();
    ans += x - now.val;
    if (link[now.id] == 0) t += 2;
    link[now.id] = 1;
    p.push({x, now.id});
  }
  printf("%lld\n", ans);
  return 0;
}
