#include <bits/stdc++.h>
using namespace std;
template <class T>
struct rge {
  T b, e;
};
template <class T>
rge<T> range(T i, T j) {
  return rge<T>{i, j};
}
template <class T>
auto dud(T *x) -> decltype(cerr << *x, 0);
template <class T>
char dud(...);
struct debug {
  template <class T>
  debug &operator<<(const T &) {
    return *this;
  }
};
const int N = 3e5 + 5;
int price[N];
int n;
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  while (cin >> n) {
    for (auto i = (0) - ((0) > (n)); i != n - ((0) > (n));
         i += 1 - 2 * ((0) > (n)))
      cin >> price[i];
    priority_queue<int> buy;
    long long money = 0;
    for (auto i = (0) - ((0) > (n)); i != n - ((0) > (n));
         i += 1 - 2 * ((0) > (n))) {
      if (!buy.empty() && -buy.top() < price[i]) {
        money += price[i] + buy.top();
        buy.pop();
        buy.emplace(-price[i]);
        buy.emplace(-price[i]);
      } else {
        buy.emplace(-price[i]);
      }
    }
    cout << money << '\n';
  }
  return 0;
}
