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