#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  vector<long long> v;
  for (int i = 0; i < n; i++) {
    long long a;
    cin >> a;
    v.push_back(a);
  }
  multiset<long long> unused, minus, plus;
  long long profit = 0;
  for (long long x : v) {
    long long a = *(plus.begin());
    long long c = *(unused.begin());
    if (unused.empty() == false && x > c) {
      if (plus.empty() == true || (c < a)) {
        plus.insert(x);
        minus.insert(c);
        unused.erase(unused.begin());
        profit += (x - c);
        continue;
      }
    }
    if (plus.empty() == false && x > a) {
      plus.erase(plus.begin());
      plus.insert(x);
      unused.insert(a);
      profit += (x - a);
      continue;
    }
    unused.insert(x);
  }
  cout << profit << "\n";
}
