#include <bits/stdc++.h>
using namespace std;
long long choose(long long n, long long k);
bool isprime(long long n);
void setprime(bool isprime[], long long n);
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  priority_queue<long long> q;
  long long n, t, ans = 0;
  cin >> n;
  cin >> t;
  q.push(t);
  for (int i = 1; i < n; i++) {
    cin >> t;
    q.push(t);
    if (t < q.top()) {
      ans += q.top() - t;
      q.pop();
      q.push(t);
    }
  }
  cout << ans;
}
long long choose(long long n, long long k) {
  if (k == 0) return 1;
  return (n * choose(n - 1, k - 1)) / k;
}
bool isprime(long long n) {
  for (long long i = 2; i * i <= n; i++) {
    if (n % i == 0) return false;
  }
  return true;
}
void setprime(bool isprime[], long long n) {
  for (int i = 0; i < n; i++) isprime[i] = true;
  isprime[0] = false;
  isprime[1] = false;
  for (int i = 2; i < n; i++) {
    for (long long j = 2; i * j < n; j++) isprime[i * j] = false;
  }
}
