#include <bits/stdc++.h>
using namespace std;
priority_queue<int, vector<int>, greater<int>> used, unused;
int main() {
  int n;
  scanf("%d", &n);
  long long ans = 0;
  while (n--) {
    int x;
    scanf("%d", &x);
    int a = INT_MAX, b = INT_MAX;
    if (!used.empty()) a = used.top();
    if (!unused.empty()) b = unused.top();
    int m = (a < b ? a : b);
    if (x < m) {
      unused.push(x);
      continue;
    }
    if (a == m) {
      ans += (long long)(x - m);
      unused.push(m);
      used.pop();
      used.push(x);
    } else {
      unused.pop();
      used.push(x);
      ans += (long long)(x - m);
    }
  }
  printf("%lld", ans);
  printf("\n");
}
