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