#include <bits/stdc++.h>
using namespace std;
priority_queue<long long> Q;
int main() {
  long long ans = 0;
  int n;
  cin >> n;
  while (n--) {
    long long a;
    cin >> a;
    Q.push(-a);
    Q.push(-a);
    ans += a + Q.top();
    Q.pop();
  }
  cout << ans << endl;
  return 0;
}
