#include <bits/stdc++.h>
using namespace std;
long long n, in[1000001], ans;
priority_queue<long long, vector<long long>, greater<long long> > q;
signed main() {
  cin >> n;
  for (long long i = 1; i <= n; i++) cin >> in[i];
  for (long long i = 1; i <= n; i++) {
    q.push(in[i]);
    if (in[i] > q.top()) {
      ans += in[i] - q.top();
      q.pop();
      q.push(in[i]);
    }
  }
  cout << ans;
}
