#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18L;
const int inf = 0x3f3f3f3f;
const int maxn = 1e5 + 5;
const int Mod = 1e9 + 7;
priority_queue<int, vector<int>, less<int> > q;
int n;
int main() {
  ios::sync_with_stdio(false);
  cin >> n;
  int p;
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    cin >> p;
    q.push(-p);
    q.push(-p);
    ans += p + q.top();
    q.pop();
  }
  cout << ans << endl;
  return 0;
}
