#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
using PII = pair<int, int>;
using LL = long long;
using ULL = unsigned long long;
using MAT = array<array<LL, 2>, 2>;
template <class T>
constexpr inline T begin(const T &) {
  return T(0);
}
template <class T>
constexpr inline T end(const T &x) {
  return max(T(0), x);
}
template <class T>
inline void _read(T &x) {
  cin >> x;
}
inline void _read(size_t &x) { scanf("%zu", &x); }
inline void _read(int &x) { scanf("%d", &x); }
inline void _read(LL &x) { scanf("%lld", &x); }
inline void _read(ULL &x) { scanf("%llu", &x); }
inline void _read(double &x) { scanf("%lf", &x); }
inline void _read(char &x) { scanf(" %c", &x); }
inline void _read(char *x) { scanf("%s", x); }
inline void read() {}
template <class T, class... U>
inline void read(T &head, U &...tail) {
  _read(head);
  read(tail...);
}
template <class T>
inline void _print(const T &x) {
  cout << x;
}
inline void _print(const size_t &x) { printf("%zu", x); }
inline void _print(const int &x) { printf("%d", x); }
inline void _print(const LL &x) { printf("%lld", x); }
inline void _print(const ULL &x) { printf("%llu", x); }
inline void _print(const double &x) { printf("%.16lf", x); }
inline void _print(const char &x) { putchar(x); }
inline void _print(const char *x) { printf("%s", x); }
inline void _print(const string &x) { printf("%s", x.c_str()); }
inline void print() { putchar('\n'); }
template <class T, class... U>
inline void print(const T &head, const U &...tail) {
  _print(head);
  if (sizeof...(tail)) putchar(' ');
  print(tail...);
}
const int MOD = 1000000007;
int main() {
  int n;
  read(n);
  priority_queue<int, vector<int>, greater<int>> pq;
  LL ans = 0;
  static_assert(std::is_same<remove_reference<decltype(n)>::type,
                             remove_reference<decltype(n)>::type>::value,
                "REP diff types");
  for (auto i = begin(n); i != end(n); ++i) {
    int p;
    read(p);
    pq.push(p);
    ans += p - pq.top();
    pq.pop();
    pq.push(p);
  }
  print(ans);
  return 0;
}
