#include <bits/stdc++.h>
using namespace std;
const int maxn = 300005;
int a[maxn], n;
bool vis[maxn];
long long ans;
priority_queue<pair<int, int>, vector<pair<int, int> >,
               greater<pair<int, int> > >
    q;
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1; i <= n; i++) {
    if (!q.empty() && q.top().first < a[i]) {
      vis[q.top().second] = !vis[q.top().second];
      ans += a[i] - q.top().first;
      if (vis[q.top().second]) q.push(q.top());
      q.pop();
      q.push(make_pair(a[i], i));
    } else {
      q.push(make_pair(a[i], i));
      vis[i] = 1;
    }
  }
  cout << ans;
  return 0;
}
