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