#include <bits/stdc++.h>
using namespace std;
long long ans;
int n, a[300005];
priority_queue<pair<int, bool>, vector<pair<int, bool>>,
               greater<pair<int, bool>>>
    q;
int main() {
  ios::sync_with_stdio(false);
  int i;
  pair<int, bool> tp;
  cin >> n;
  for (i = 1; i <= n; i++) cin >> a[i];
  for (i = 1; i <= n; i++) {
    if (!q.empty() && (tp = q.top()).first < a[i]) {
      q.pop();
      if (!tp.second) q.push(make_pair(tp.first, true));
      q.push(make_pair(a[i], false));
      ans += a[i] - tp.first;
    } else
      q.push(make_pair(a[i], true));
  }
  cout << ans << endl;
  return 0;
}
