#include <bits/stdc++.h>
using namespace std;
priority_queue<int> q;
int main() {
  int n;
  cin >> n;
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    int a;
    cin >> a;
    if (q.empty() || a >= q.top())
      q.push(a);
    else
      ans += q.top() - a, q.pop(), q.push(a), q.push(a);
  }
  cout << ans << endl;
  return 0;
}
