#include <bits/stdc++.h>
using namespace std;
long long n, m, p, k, ans, sum, tot, a[300002];
priority_queue<long long, vector<long long>, greater<long long> > q;
inline long long read() {
  register long long x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (isdigit(ch)) {
    x = (x << 1) + (x << 3) + (ch ^ 48);
    ch = getchar();
  }
  return x * f;
}
signed main() {
  n = read();
  for (long long i = 1; i <= n; i++) {
    a[i] = read();
    if (!q.empty() && q.top() < a[i]) {
      ans += a[i] - q.top();
      q.pop();
      q.push(a[i]);
    }
    q.push(a[i]);
  }
  printf("%lld", ans);
  return 0;
}
