#include <bits/stdc++.h>
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
  std::cout << name << " : " << arg1 << '\n';
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
  const char* comma = strchr(names + 1, ',');
  std::cout.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long i, j, n, m, k, cnt = 0, ans = 0, t = 1;
  cin >> n;
  long long a[n];
  for (i = 0; i < n; i++) cin >> a[i];
  priority_queue<long long, vector<long long>, greater<long long> > pq;
  for (i = 0; i < n; i++) {
    if (!pq.empty() && pq.top() < a[i]) {
      ans += (a[i] - pq.top());
      pq.pop();
      pq.push(a[i]);
    }
    pq.push(a[i]);
  }
  return cout << ans, 0;
  return 0;
}
