#include <bits/stdc++.h>
using namespace std;
int A[300005] = {0}, arr[300002];
int adj[550][550];
int main() {
  int n;
  cin >> n;
  priority_queue<pair<int, int>, vector<pair<int, int> >,
                 greater<pair<int, int> > >
      pq;
  int i;
  long long int ans = 0;
  for (i = 1; i <= n; i++) {
    int p;
    cin >> p;
    arr[i] = p;
    if (pq.size()) {
      if (pq.top().first < p) {
        ans += p - pq.top().first;
        A[i] = pq.top().second;
        if (A[pq.top().second])
          A[pq.top().second] = 0;
        else
          pq.pop();
      }
    }
    pq.push(make_pair(arr[i], i));
  }
  cout << ans;
  return 0;
}
