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