#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long sum = 0, k = 1;
  char c = getchar();
  for (; c < '0' || c > '9'; c = getchar())
    if (c == '-') k = -1;
  for (; c <= '9' && c >= '0'; c = getchar()) sum = sum * 10 + c - '0';
  return sum * k;
}
priority_queue<long long, vector<long long>, greater<long long> > q;
long long n;
signed main() {
  n = read();
  long long a = 0;
  long long ans = 0;
  for (long long i = 1; i <= n; i++) {
    a = read();
    q.push(a);
    if (!q.empty() && a > q.top()) {
      ans += a - q.top();
      q.pop();
      q.push(a);
    }
  }
  cout << ans;
  return 0;
}
