#include <bits/stdc++.h>
using namespace std;
priority_queue<pair<long long, long long>, vector<pair<long long, long long> >,
               less<pair<long long, long long> > >
    q;
int T;
long long ans, n, m, cnt, x;
int main() {
  while (~scanf("%lld", &n)) {
    while (!q.empty()) q.pop();
    ans = 0;
    cnt = 0;
    for (int i = 1; i <= n; i++) {
      scanf("%lld", &x);
      q.push(make_pair(-x, 1));
      q.push(make_pair(-x, 0));
      ans += x + q.top().first;
      if (!q.top().second) cnt += 2;
      q.pop();
    }
    printf("%lld\n", ans);
  }
}
