#include <bits/stdc++.h>
using namespace std;
int n;
int main() {
  multiset<int> Q;
  cin >> n;
  long long ans = 0;
  long long times = 0;
  bool b = false;
  int count = 0;
  for (int i = 0; i < n; i++) {
    int x;
    cin >> x;
    if (Q.size() == 0 || (*Q.begin()) > x) {
      Q.insert(x);
    } else {
      ans += x - *Q.begin();
      if (b) {
        times += 2;
        count++;
        if (count == 2) {
          b = false;
          count = 0;
        }
      } else
        b = true;
      Q.erase(Q.begin());
      Q.insert(x);
      Q.insert(x);
    }
  }
  cout << ans << endl;
}
