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