#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n;
  cin >> n;
  vector<int> p(n);
  for (int i = 0; i < n; ++i) {
    cin >> p[i];
  }
  long long ans = 0;
  priority_queue<pair<int, int>> pq;
  for (int i = n - 1; i >= 0; --i) {
    if (pq.empty())
      pq.push({p[i], -1});
    else {
      if (pq.top().first > p[i]) {
        auto x = pq.top();
        pq.pop();
        ans += x.first - p[i];
        if (x.second != -1) {
          pq.push({x.first, -1});
        }
        pq.push({p[i], 1});
      } else {
        pq.push({p[i], -1});
      }
    }
  }
  cout << ans << endl;
}
