#include <bits/stdc++.h>
using namespace std;
priority_queue<long long> Q;
long long n, x, ans;
signed main() {
  scanf("%lld", &n);
  for (long long i = 1; i <= n; i++) {
    scanf("%lld", &x);
    Q.push(x);
    if (Q.top() > x) {
      ans += Q.top() - x;
      Q.pop();
      Q.push(x);
    }
  }
  return cout << ans, 0;
}
