#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
int n;
int num;
long long ans = 0;
priority_queue<int> q;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &num);
    q.push(num);
    if (num < q.top()) {
      ans += (long long)q.top() - (long long)num;
      q.pop();
      q.push(num);
    }
  }
  printf("%lld\n", ans);
  return 0;
}
