#include <bits/stdc++.h>
using namespace std;
long long mod = 1000000007;
long long n, a[300009], ans;
priority_queue<long long, vector<long long>, greater<long long> > pq;
signed main() {
  ios_base::sync_with_stdio(0);
  cin >> n;
  for (long long i = 1; i <= n; i++) cin >> a[i];
  for (long long i = 1; i <= n; i++) {
    if (pq.empty())
      pq.push(a[i]);
    else {
      if (pq.top() < a[i]) ans += a[i] - pq.top(), pq.pop(), pq.push(a[i]);
      pq.push(a[i]);
    }
  }
  cout << ans;
}
