#include <bits/stdc++.h>
using namespace std;
long long n, ans;
priority_queue<long long, vector<long long>, greater<long long> > q;
signed main() {
  ios::sync_with_stdio(0);
  cin >> n;
  while (n--) {
    long long x;
    cin >> x;
    if (!q.empty() && q.top() < x) ans += x - q.top(), q.pop(), q.push(x);
    q.push(x);
  }
  cout << ans << endl;
}
