#include <bits/stdc++.h>
using namespace std;
int mas[300001];
signed main() {
  int n;
  cin >> n;
  multiset<pair<int, int> > sss;
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &mas[i]);
  }
  for (int i = n; i >= 1; --i) {
    int cur = mas[i];
    if (sss.size() && sss.rbegin()->first > cur) {
      pair<int, int> curp = *sss.rbegin();
      sss.erase(--sss.end());
      if (curp.first == curp.second) {
        sss.insert(make_pair(cur, curp.second));
      } else {
        sss.insert(make_pair(curp.first, curp.first));
        sss.insert(make_pair(cur, curp.second));
      }
    } else {
      sss.insert(make_pair(cur, cur));
    }
  }
  long long ans = 0;
  for (auto it : sss) {
    ans += it.second - it.first;
  }
  cout << ans << endl;
}
