#include <bits/stdc++.h>
using namespace std;
int a[300005];
multiset<int> ms;
multiset<pair<int, int> > vis;
int main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  long long ans = 0;
  for (int i = n; i >= 1; i--) {
    if (!vis.empty()) {
      int x = -vis.begin()->first;
      if (x > a[i]) {
        int y = vis.begin()->second;
        vis.erase(vis.begin());
        ans += x - a[i];
        vis.insert(pair<int, int>(-a[i], y));
        a[i] = x;
      }
    }
    if (!ms.empty() && -*ms.begin() > a[i]) {
      int mx = -*ms.begin();
      ms.erase(ms.begin());
      ans += mx - a[i];
      vis.insert(pair<int, int>(-a[i], mx));
    } else
      ms.insert(-a[i]);
  }
  cout << ans << endl;
}
