#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  long long ans = 0;
  priority_queue<int, vector<int>, greater<int> > q;
  scanf("%d", &n);
  while (n--) {
    int x;
    scanf("%d", &x);
    if (q.size() == 0)
      q.push(x);
    else {
      int y = q.top();
      if (y > x)
        q.push(x);
      else {
        q.pop();
        ans += x - y;
        q.push(x);
        q.push(x);
      }
    }
  }
  printf("%lld\n", ans);
}
