#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, i = 0, x;
  long long ans = 0;
  priority_queue<int, vector<int>, greater<int>> q;
  for (scanf("%d", &n); i < n && scanf("%d", &x) || (printf("%I64d\n", ans), 0);
       q.push(x), ++i)
    if (q.size() && q.top() <= x) ans += x - q.top(), q.pop(), q.push(x);
  return 0;
}
