#include <bits/stdc++.h>
using namespace std;
const int N = 3 * 1e5 + 5;
int n, a[N];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  priority_queue<int, vector<int>, greater<int> > Q;
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    if (Q.empty()) {
      Q.push(a[i]);
      continue;
    }
    int t = Q.top();
    if (t >= a[i])
      Q.push(a[i]);
    else {
      ans += a[i] - t;
      Q.pop();
      Q.push(a[i]);
      Q.push(a[i]);
    }
  }
  printf("%I64d\n", ans);
  return 0;
}
