#include <bits/stdc++.h>
using namespace std;
int rd() {
  int tt;
  scanf("%d", &tt);
  return tt;
}
priority_queue<int, vector<int>, greater<int> > q;
signed main() {
  int n;
  cin >> n;
  long long ans = 0;
  while (n--) {
    int tem = rd();
    if (q.size() and q.top() < tem) {
      ans += tem - q.top();
      q.pop();
      q.push(tem);
    }
    q.push(tem);
  }
  cout << ans << '\n';
  return 0;
}
