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