#include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 10;
const int inf = 0x3f3f3f3f;
int n, cnt;
int a[maxn], flag[maxn], cover[maxn << 2];
long long Ans;
struct Node {
  int val, flag;
  bool operator>(const Node &b) const {
    if (val == b.val) return flag < b.flag;
    return val > b.val;
  }
};
priority_queue<Node, vector<Node>, greater<Node>> q;
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  Node tmp;
  tmp.flag = 0;
  tmp.val = a[1];
  q.push(tmp);
  for (int i = 2; i <= n; i++) {
    if (q.empty() || q.top().val >= a[i]) {
      tmp.flag = 0;
      tmp.val = a[i];
      q.push(tmp);
    } else {
      tmp = q.top();
      if (tmp.flag == 1) {
        Ans += 1LL * a[i] - 1LL * tmp.val;
        q.pop();
        tmp.flag = 0;
        q.push(tmp);
        tmp.flag = 1;
        tmp.val = a[i];
        q.push(tmp);
      } else {
        q.pop();
        cnt++;
        Ans += 1LL * a[i] - 1LL * tmp.val;
        tmp.flag = 1;
        tmp.val = a[i];
        q.push(tmp);
      }
    }
  }
  cout << Ans << endl;
  return 0;
}
