#include <bits/stdc++.h>
using namespace std;
long long T, n, par[400010], cnt;
long long ans;
struct node {
  long long pos;
  long long val;
  bool operator<(node b) const {
    if (val == b.val) return pos < b.pos;
    return val > b.val;
  }
};
priority_queue<node> q;
int main() {
  T = 1;
  while (T--) {
    scanf("%lld", &n);
    long long x, z, y;
    memset(par, 0, sizeof(par));
    while (!q.empty()) q.pop();
    ans = 0;
    cnt = 0;
    for (long long i = 1; i <= n; i++) {
      scanf("%lld", &x);
      if (!q.empty() && q.top().val < x) {
        node pre = q.top();
        y = pre.val;
        z = pre.pos;
        par[i] = 1;
        if (par[z] == 0) {
          cnt++;
          ans += x - y;
          q.pop();
        } else {
          ans += x - y;
          par[z] = 0;
        }
      }
      node tmp;
      tmp.val = x;
      tmp.pos = i;
      q.push(tmp);
    }
    printf("%lld\n", ans);
  }
  return 0;
}
