#include <bits/stdc++.h>
using namespace std;
priority_queue<long long, vector<long long>, greater<long long> > b;
long long n, t;
long long ans = 0;
int main() {
  scanf("%lld", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &t);
    b.push(t);
    if (b.top() < t) {
      ans += t - b.top();
      b.pop();
      b.push(t);
    }
  }
  printf("%lld", ans);
}
