#include <bits/stdc++.h>
using namespace std;
const long long maxn = 3e5 + 10;
priority_queue<long long, vector<long long>, greater<long long> > qu;
signed main() {
  long long n;
  cin >> n;
  long long m;
  long long ans = 0;
  for (long long i = 0; i < n; i++) {
    cin >> m;
    if (qu.size() && m > qu.top()) {
      ans += (m - qu.top());
      qu.pop();
      qu.push(m);
    }
    qu.push(m);
  }
  cout << ans << endl;
}
