#include <bits/stdc++.h>
using namespace std;
multiset<long long> ms;
long long n, x, ans;
void solve() {
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> x;
    if (ms.size() && *ms.begin() < x) {
      auto it = ms.begin();
      ans += x - *it;
      ms.insert(x);
      ms.erase(it);
    }
    ms.insert(x);
  }
  cout << ans;
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  solve();
  return 0;
}
