#include <bits/stdc++.h>
using namespace std;
void work() {
  int n, t;
  long long ans = 0;
  std::priority_queue<int> Q;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &t);
    if (i == 1) {
      Q.push(t);
      continue;
    }
    int j;
    if (Q.top() <= t) {
      Q.push(t);
    } else {
      ans += Q.top() - t;
      Q.pop();
      Q.push(t);
      Q.push(t);
    }
    j = Q.top();
  }
  printf("%lld\n", ans);
}
int main() {
  int T;
  T = 1;
  while (T--) work();
  return 0;
}
