#include <bits/stdc++.h>
using namespace std;
priority_queue<int> q;
int main() {
  int N, p;
  long long ans = 0;
  cin >> N;
  while (N--) {
    scanf("%d", &p);
    q.push(-p);
    q.push(-p);
    ans += p + q.top();
    q.pop();
  }
  cout << ans;
  return 0;
}
