#include <bits/stdc++.h>
using namespace std;
priority_queue<int> pri;
int read() {
  int A;
  bool K;
  char C;
  C = A = K = 0;
  while (C < '0' || C > '9') K |= C == '-', C = getchar();
  while (C > '/' && C < ':') A = (A << 3) + (A << 1) + (C ^ 48), C = getchar();
  return (K ? -A : A);
}
int main() {
  long long s = 0;
  int a, n;
  n = read();
  while (n--) {
    a = read();
    pri.push(a);
    if (pri.top() > a) {
      s += pri.top() - a;
      pri.pop();
      pri.push(a);
    }
  }
  cout << s;
  return 0;
}
