#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  int arr[n];
  long long int ans = 0;
  priority_queue<long long int> pq;
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
  }
  for (int i = 0; i < n; i++) {
    int x = arr[i];
    if (pq.empty() || (-pq.top()) > arr[i])
      pq.push(-x);
    else {
      ans += pq.top() + arr[i];
      pq.pop();
      pq.push(-x);
      pq.push(-x);
    }
  }
  cout << ans;
}
