#include <bits/stdc++.h>
using namespace std;
class prior {
 public:
  bool operator()(int a, int b) const { return a > b; }
};
int main() {
  int n;
  scanf("%d", &n);
  priority_queue<int, vector<int>, prior> q;
  long long ans = 0;
  while (n--) {
    int x;
    scanf("%d", &x);
    if (q.size() && q.top() < x) {
      ans += x - q.top();
      q.pop();
      q.push(x);
    }
    q.push(x);
  }
  printf("%I64d", ans);
  return 0;
}
