#include <bits/stdc++.h>
using namespace std;
const int inf = ~0u >> 1, MOD = 1e9 + 7;
char *TT, *mo, but[(1 << 15) + 2];
inline int rd() {
  int first = 0, c = 0, f = 1;
  for (; c < '0' || c > '9';
       c = ((TT == mo &&
             (mo = ((TT = but) + fread(but, 1, 1 << 15, stdin)), TT == mo))
                ? -1
                : *TT++))
    f = c != '-';
  for (; c >= '0' && c <= '9';
       c = ((TT == mo &&
             (mo = ((TT = but) + fread(but, 1, 1 << 15, stdin)), TT == mo))
                ? -1
                : *TT++))
    first = first * 10 + c - '0';
  return f ? first : -first;
}
multiset<int> S;
int main() {
  int n = rd();
  long long ans = 0;
  for (int i = (1), i_end = (n); i <= i_end; i++) {
    int first = rd();
    if (S.size() && first > *S.begin()) {
      ans += first - *S.begin();
      S.erase(S.begin());
      S.insert(first);
    }
    S.insert(first);
  }
  cout << ans << endl;
}
