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