#include <bits/stdc++.h>
using namespace std;
long long gi() {
  char x = getchar();
  long long t = 0, fh = 1;
  while (x < '0' || x > '9') {
    if (x == '-') fh = -1;
    x = getchar();
  }
  while (x >= '0' && x <= '9') {
    t = t * 10 + x - '0';
    x = getchar();
  }
  return fh * t;
}
long long n, ans, x;
priority_queue<long long> q;
int main() {
  n = gi();
  for (int i = 1; i <= n; i++) {
    x = gi();
    q.push(x);
    long long k = q.top();
    if (x < k) {
      ans += k - x;
      q.pop();
      q.push(x);
    }
  }
  printf("%lld", ans);
  return 0;
}
