#include <bits/stdc++.h>
using namespace std;
template <class T>
void in(T &x) {
  x = 0;
  bool flag = 0;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') flag = 1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = (x << 3) + (x << 1) + (c ^ 48);
    c = getchar();
  }
  if (flag) x = -x;
}
priority_queue<long long, vector<long long>, greater<long long> > q;
long long n, x, ans;
signed main() {
  in(n);
  for (register long long i = 1; i <= n; ++i) {
    in(x);
    q.push(x);
    long long tmp = q.top();
    if (x > tmp) ans += x - tmp, q.pop(), q.push(x);
  }
  printf("%lld", ans);
}
