#include <bits/stdc++.h>
const int MX = 1e5 + 23;
const long long MOD = 998244353;
int read() {
  char k = getchar();
  int x = 0;
  while (k < '0' || k > '9') k = getchar();
  while (k >= '0' && k <= '9') x = x * 10 + k - '0', k = getchar();
  return x;
}
int n;
int main() {
  n = read();
  long long ans = 0;
  std::priority_queue<int, std::vector<int>, std::greater<int> > q;
  for (int i = 1, a; i <= n; ++i) {
    a = read();
    if (!q.empty() && q.top() < a) {
      ans += a - q.top();
      q.pop();
      q.push(a);
    }
    q.push(a);
  }
  printf("%lld\n", ans);
  return 0;
}
