#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  long long ans = 0;
  priority_queue<int, vector<int>, greater<int>> pq;
  while (n--) {
    int x;
    cin >> x;
    if (pq.size() && x > pq.top()) {
      ans += x - pq.top();
      pq.pop();
      pq.push(x);
    }
    pq.push(x);
  }
  cout << ans;
  return 0;
}
