#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O2,no-stack-protector,unroll-loops,fast-math")
const long long maxn = 1e5 + 10, maxm = 1e6 + 10, lg = 21, mod = 1e9 + 7,
                inf = 1e18;
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  long long n, ans = 0;
  cin >> n;
  priority_queue<long long, vector<long long>, greater<long long>> pq;
  while (n--) {
    long long x;
    cin >> x;
    if (!pq.empty() && pq.top() < x) {
      ans += x - pq.top();
      pq.pop();
      pq.push(x);
    }
    pq.push(x);
  }
  cout << ans;
  return 0;
}
