#include <bits/stdc++.h>
using namespace std;
const int N = 500010;
long long n, x, ans;
priority_queue<long long> q;
int main() {
  scanf("%lld", &n);
  while (n--) {
    scanf("%lld", &x);
    q.push(x);
    if (q.top() != x) {
      ans += (q.top() - x);
      q.pop();
      q.push(x);
    }
  }
  printf("%lld\n", ans);
  return 0;
}
