#include <bits/stdc++.h>
using namespace std;
const long long infll = powl(2, 62) - 1;
const long double pi = 4.0 * atanl(1.0);
const long long mod = powl(10, 9) + 7;
int32_t main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long n;
  cin >> n;
  vector<long long> arr(n);
  for (long long &x : arr) cin >> x;
  priority_queue<long long> p;
  long long profit = 0;
  for (long long &x : arr) {
    p.push(-x);
    long long least = -p.top();
    if (least < x) {
      profit += x - least;
      p.pop();
      p.push(-x);
    }
  }
  cout << profit << '\n';
  return 0;
}
