#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1);
const long long mod = 1e9 + 7;
inline long long read() {
  long long x = 0, f = 1;
  char ch = getchar();
  while (ch > '9' || ch < '0') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
int n, k, m, t;
int a[300005];
priority_queue<long long, vector<long long>, greater<long long>> Q;
long long ans;
int main() {
  int i, j;
  n = read();
  for (i = 1; i <= n; i++) a[i] = read();
  for (i = 1; i <= n; i++) {
    if (Q.empty())
      Q.push(a[i]);
    else {
      long long tp = Q.top();
      if (a[i] > tp) ans += a[i] - tp, Q.pop(), Q.push(a[i]);
      Q.push(a[i]);
    }
  }
  printf("%lld", ans);
  return 0;
}
