#include <bits/stdc++.h>
using namespace std;
long long arr[1000005] = {0};
int main() {
  long long i, j, n, mn = 0, xm, ans = 0, mi, q;
  cin >> n;
  multiset<long long> s;
  multiset<long long>::iterator it;
  for (i = 0; i < n; i++) {
    cin >> j;
    if (s.size() > 0 && (q = *s.begin()) < j) {
      ans += j - q, arr[j] += 1;
      if (arr[q] > 0)
        arr[q] -= 1;
      else
        s.erase(s.begin());
    }
    s.insert(j);
  }
  cout << ans;
}
