#include <bits/stdc++.h>
int n;
long long answer, x;
std::priority_queue<int> q;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &x);
    q.push(-x);
    q.push(-x);
    answer += x + q.top();
    q.pop();
  }
  printf("%lld", answer);
  return 0;
}
