#include <bits/stdc++.h>
using namespace std;
priority_queue<long long> heap;
long long n, a[5005];
int main() {
  cin >> n;
  long long ans = 0;
  for (long long i = 1; i <= n; i++) cin >> a[i];
  for (long long i = 1; i <= n; i++) {
    if (!heap.empty() && heap.top() > a[i]) {
      ans += heap.top() - a[i];
      heap.pop();
      heap.push(a[i]);
    }
    heap.push(a[i]);
  }
  cout << ans;
}
