#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  scanf("%d", &n);
  priority_queue<int, vector<int>, greater<int> > a;
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    long long x;
    scanf("%lld", &x);
    ans -= x;
    a.push(x);
    a.push(x);
    ans += a.top();
    a.pop();
  }
  printf("%lld", -1 * ans);
  return 0;
}
