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