#include <bits/stdc++.h>
using namespace std;
int n, a[300005];
long long ans;
priority_queue<pair<int, int> > q;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    int x;
    scanf("%d", &x);
    if (!q.size())
      q.push(make_pair(-x, 0));
    else if (x + q.top().first <= 0)
      q.push(make_pair(-x, 0));
    else {
      int cur = q.top().first, op = q.top().second;
      q.pop();
      ans += x + cur, q.push(make_pair(-x, 1));
      if (op) q.push(make_pair(cur, 0));
    }
  }
  printf("%lld\n", ans);
  return 0;
}
