#include <bits/stdc++.h>
using namespace std;
int n, x;
long long ans;
multiset<int> ms;
int main() {
  cin >> n;
  while (n--)
    cin >> x, ms.insert(x), ms.insert(x), ms.erase(ms.begin()), ans -= x;
  for (auto i : ms) ans += i;
  cout << ans;
}
