#include <bits/stdc++.h>
using namespace std;
int dX[] = {0, 0, 1, -1, 1, -1, 1, -1};
int dY[] = {1, -1, 0, 0, 1, -1, -1, 1};
int main() {
  int n, x, b, s;
  multiset<int> Maybuy, sold;
  long long ans = 0;
  scanf("%d", &n);
  while (n--) {
    scanf("%d", &x);
    b = s = 2000000100;
    if (!Maybuy.empty()) b = *Maybuy.begin();
    if (!sold.empty()) s = *sold.begin();
    if (x > s || x > b) {
      if (s > b) {
        ans += (x - b);
        Maybuy.erase(Maybuy.begin());
        sold.insert(x);
      } else {
        ans += (x - s);
        sold.erase(sold.begin());
        sold.insert(x);
        Maybuy.insert(s);
      }
    } else
      Maybuy.insert(x);
  }
  cout << ans;
  return 0;
}
