#include <bits/stdc++.h>
using namespace std;
int read() {
  int x = 0, f = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (!(c < '0' || c > '9')) {
    x = x * 10 + c - '0';
    c = getchar();
  }
  return x * f;
}
int n;
long long ans;
priority_queue<int, vector<int>, greater<int> > q;
int main() {
  n = read();
  for (int i = 1; i <= n; i++) {
    int x = read();
    if (!q.empty() && q.top() < x) {
      ans += x - q.top();
      q.pop();
      q.push(x);
    }
    q.push(x);
  }
  cout << ans;
  return 0;
}
