#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3 * 100 * 1000 + 17;
long long n, a[MAXN];
long long ans;
multiset<long long> s;
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) {
    s.insert(a[i]);
    if (*s.begin() < a[i]) {
      long long tmp = *s.begin();
      s.erase(s.begin());
      ans += a[i] - tmp;
      s.insert(a[i]);
    }
  }
  cout << ans << endl;
  return 0;
}
