#include <bits/stdc++.h>
using namespace std;
const int maxn = 300001;
int n, pi;
long long ans = 0;
priority_queue<int, vector<int>, greater<int> > q;
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> pi;
    if (!q.empty() && q.top() < pi) {
      ans += pi - q.top();
      q.pop();
      q.push(pi);
    }
    q.push(pi);
  }
  cout << ans << endl;
  return 0;
}
