#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
priority_queue<int, vector<int>, greater<int> > q;
int main() {
  int n;
  scanf("%d", &n);
  long long sum = 0;
  for (int i = 1; i <= n; i++) {
    int x;
    scanf("%d", &x);
    if (q.size() && q.top() < x) sum += x - q.top(), q.pop(), q.push(x);
    q.push(x);
  }
  cout << sum << endl;
  return 0;
}
