#include <bits/stdc++.h>
using namespace std;
priority_queue<int, vector<int>, greater<int> > q;
int main() {
  int n, m;
  while (cin >> n) {
    long long sum = 0;
    if (!q.empty()) {
      q.pop();
    }
    while (n--) {
      scanf("%d", &m);
      if (!q.empty() && m > q.top()) {
        sum += m - q.top();
        q.pop();
        q.push(m);
        q.push(m);
      } else {
        q.push(m);
      }
    }
    cout << sum << endl;
  }
  return 0;
}
