#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5, inf32 = 1e9 + 9;
const long long inf64 = 1e18 + 18;
int main() {
  int n, a;
  multiset<int> unused, used, sold;
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) {
    scanf("%d", &a);
    if (unused.size() && *(unused.begin()) < a &&
        (sold.empty() || *(sold.begin()) > *(unused.begin()))) {
      sold.insert(a);
      used.insert(*(unused.begin()));
      unused.erase(unused.begin());
    } else if (sold.size() && *(sold.begin()) < a) {
      unused.insert(*(sold.begin()));
      sold.erase(sold.begin());
      sold.insert(a);
    } else
      unused.insert(a);
  }
  long long sum = 0;
  for (auto &x : sold) sum += x;
  for (auto &x : used) sum -= x;
  cout << sum;
  return 0;
}
