#include <bits/stdc++.h>
using namespace std;
long long n, ans, val[3001000];
priority_queue<int> q;
int main() {
  scanf("%lld", &n);
  for (int i = 1; i <= n; i++) scanf("%lld", &val[i]);
  for (int i = 1; i <= n; i++) {
    q.push(-val[i]);
    q.push(-val[i]);
    ans += val[i] + q.top();
    q.pop();
  }
  printf("%lld\n", ans);
  return 0;
}
