#include <bits/stdc++.h>
using namespace std;
multiset<int> a, b;
int main() {
  int n, i, q, c;
  long long ans = 0;
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> q;
    int c = 1e9;
    int d = 1e9;
    if (a.size()) {
      c = *a.begin();
    }
    if (b.size()) {
      d = *b.begin();
    }
    if (c > d) {
      if (q > d) {
        ans += (q - d);
        b.erase(b.begin());
        a.insert(q);
      } else {
        b.insert(q);
      }
    } else {
      if (q > c) {
        a.erase(a.begin());
        a.insert(q);
        b.insert(c);
        ans += (q - c);
      } else {
        b.insert(q);
      }
    }
  }
  cout << ans;
}
