#include <bits/stdc++.h>
char BB[1 << 17], *SS = BB, *TT = BB;
inline int Read() {
  register int x = 0, f = 1;
  register char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch <= '9' && ch >= '0') {
    x = x * 10 + (ch ^ 48);
    ch = getchar();
  }
  return f < 0 ? (~x) + 1 : x;
}
inline int Min(const int a, const int b) { return a < b ? a : b; }
std::priority_queue<int> q;
int main() {
  long long ans = 0, x;
  int n;
  n = Read();
  for (int i = 1; i <= n; ++i) {
    q.push(x = Read());
    if (x < q.top()) {
      ans += q.top() - x;
      q.pop();
      q.push(x);
    }
  }
  printf("%lld\n", ans);
  return 0;
}
