#include <bits/stdc++.h>
const int MAXN = 200000;
using namespace std;
inline int read() {
  int x = 0, w = 1;
  char c = ' ';
  while (!isdigit(c)) {
    c = getchar();
    if (c == '-') w = -1;
  }
  while (isdigit(c)) {
    x = (x << 1) + (x << 3) + (c ^ 48);
    c = getchar();
  }
  return x * w;
}
priority_queue<int, vector<int>, greater<int> > pq;
int n;
void init() { n = read(); }
int main() {
  init();
  long long ans = 0;
  for (int i = 1; i <= n; ++i) {
    int x = read();
    pq.push(x), pq.push(x);
    ans += x - pq.top();
    pq.pop();
  }
  printf("%I64d\n", ans);
}
