#include <bits/stdc++.h>
using namespace std;
int main() {
  priority_queue<long long, vector<long long>, greater<long long> > q;
  long long n;
  cin >> n;
  long long ans = 0;
  for (long long i = 1; i <= n; i++) {
    long long x;
    cin >> x;
    if (!q.empty() && q.top() < x) {
      ans += x - q.top();
      q.pop();
      q.push(x);
    }
    q.push(x);
  }
  cout << ans;
  return 0;
}
