#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
priority_queue<int, vector<int>, greater<int> > q;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, a;
  cin >> n;
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    cin >> a;
    if (q.empty() || a <= q.top()) {
      q.push(a);
    } else {
      ans += a - q.top();
      q.pop();
      q.push(a);
      q.push(a);
    }
  }
  cout << ans << endl;
  return 0;
}
