#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  long long resp = 0;
  multiset<long long> vendo;
  scanf("%d", &n);
  while (n--) {
    long long val;
    scanf("%lld", &val);
    vendo.insert(val);
    vendo.insert(val);
    vendo.erase(vendo.begin());
    resp -= val;
  }
  for (auto x : vendo) resp += x;
  printf("%lld\n", resp);
  return 0;
}
