#include <bits/stdc++.h>
using namespace std;
long long ans;
priority_queue<int, vector<int>, greater<int> > q;
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    int x;
    scanf("%d", &x);
    if (!q.empty() && q.top() < x) {
      ans += (long long)(x)-q.top();
      q.pop();
      q.push(x);
    }
    q.push(x);
  }
  cout << ans << endl;
}
