#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, tmp;
  long long ans = 0;
  priority_queue<int, vector<int>, greater<int> > min_p;
  while (!min_p.empty()) min_p.pop();
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &tmp);
    if (!min_p.empty() && tmp > min_p.top()) {
      ans += (long long)(tmp - min_p.top());
      min_p.pop();
      min_p.push(tmp);
    }
    min_p.push(tmp);
  }
  printf("%I64d\n", ans);
  return 0;
}
