#include <bits/stdc++.h>
using namespace std;
const long long Llinf = LLONG_MAX;
const int Inf = INT_MAX;
const int Maxn = 1e5 + 10;
const int Mod = 1e9 + 7;
char* _c = new char[Maxn];
string GetString() {
  scanf("%s", _c);
  return string(_c);
}
int n;
priority_queue<int, vector<int>, greater<int> > Q;
long long ans;
int main() {
  scanf("%d", &n);
  for (int i = 0, a; i < n; i++) {
    scanf("%d", &a);
    if (Q.empty() || a < Q.top())
      Q.push(a);
    else {
      ans += a - Q.top();
      Q.pop();
      Q.push(a), Q.push(a);
    }
  }
  printf("%I64d\n", ans);
  return 0;
}
