#include <bits/stdc++.h>
using namespace std;
long long int n, num;
long long int sum;
int main() {
  while (scanf("%lld", &n) != EOF) {
    sum = 0;
    priority_queue<int, vector<int>, greater<int>> q;
    while (!q.empty()) {
      q.pop();
    }
    while (n--) {
      scanf("%lld", &num);
      q.push(num);
      if (num > q.top() && !q.empty()) {
        sum += num - q.top();
        q.pop();
        q.push(num);
      }
    }
    printf("%lld\n", sum);
  }
}
