#include <bits/stdc++.h>
using namespace std;
struct node {
  long long int a;
  node() {}
  node(int x) { a = x; }
};
bool operator<(node as, node bs) { return as.a > bs.a; }
int main() {
  priority_queue<node> pq;
  long long int n, u, ans = 0;
  cin >> n;
  for (long long int i = 0; i < n; i++) {
    cin >> u;
    pq.push(u);
    if (pq.top().a < u) {
      long long int x = pq.top().a;
      pq.pop();
      ans += (u - x);
      pq.push(u);
    }
  }
  cout << ans << endl;
  return 0;
}
