#include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 10;
int n, w[maxn];
long long ans = 0;
priority_queue<int, vector<int>, greater<int> > q;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &w[i]);
  q.push(w[1]);
  for (int i = 2; i <= n; i++) {
    int minw = q.top();
    if (w[i] < minw)
      q.push(w[i]);
    else {
      ans += w[i] - minw;
      q.pop();
      q.push(w[i]);
      q.push(w[i]);
    }
  }
  cout << ans << endl;
  return 0;
}
