#include <bits/stdc++.h>
void nop();
using namespace std;
const int inf = (int)1e9;
const long long infl = (long long)2e18;
const int mod = 1000000007;
int main() {
  int n;
  cin >> n;
  vector<int> p(n);
  for (int i = 0; i < n; ++i) {
    cin >> p[i];
  }
  multiset<int> a;
  long long ans = 0;
  for (int i = 0; i < n; ++i) {
    if (!a.empty() && *a.begin() < p[i]) {
      ans += p[i] - *a.begin();
      a.erase(a.begin());
      a.insert(p[i]);
    }
    a.insert(p[i]);
  }
  cout << ans << endl;
  return 0;
}
