#include <bits/stdc++.h>
using namespace std;
int main() {
  priority_queue<long long, vector<long long>, greater<long long> > q;
  long long p, a, ans = 0;
  scanf("%lld", &p);
  while (p--) {
    scanf("%lld", &a);
    if (q.size() && q.top() < a) {
      ans = ans + a - q.top();
      q.pop();
      q.push(a);
    }
    q.push(a);
  }
  printf("%lld\n", ans);
}
