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