#include <bits/stdc++.h>
using namespace std;
priority_queue<long long> Q;
int N;
long long Ans, p;
int main() {
  scanf("%d", &N);
  for (register int i = (1); i <= (N); ++i) {
    scanf("%I64d", &p);
    if (!Q.empty() && p > -Q.top()) Ans += p + Q.top(), Q.pop(), Q.push(-p);
    Q.push(-p);
  }
  printf("%I64d\n", Ans);
  return 0;
}
