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