#include <bits/stdc++.h>
using namespace std;
bool sell[300005];
int main() {
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, i, x;
  set<pair<int, int> > s;
  long long res = 0;
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> x;
    if (s.empty() || s.begin()->first >= x) {
      s.insert({x, i});
      continue;
    }
    res += x - s.begin()->first;
    if (sell[s.begin()->second])
      sell[s.begin()->second] = false;
    else
      s.erase(s.begin());
    sell[i] = true;
    s.insert({x, i});
  }
  cout << res;
  return 0;
}
