#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
const int INF = 1e9 + 7;
const int N = 3e5 + 7;
const int M = 1e6 + 7;
priority_queue<long long> q;
signed main() {
  ios::sync_with_stdio(false);
  int n;
  cin >> n;
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    long long x;
    cin >> x;
    q.push(-x);
    if (-q.top() < x) {
      ans += x - (-q.top());
      q.pop();
      q.push(-x);
    }
  }
  cout << ans << endl;
  return 0;
}
