#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, m, i, j, k, x, y, t;
  cin >> n;
  priority_queue<long long, vector<long long>, greater<long long>> q;
  long long ans = 0;
  for (i = 0; i < n; i++) {
    cin >> x;
    q.push(x);
    if (x > q.top()) {
      ans += x - q.top();
      q.pop();
      q.push(x);
    }
  }
  printf("%lld\n", ans);
}
