#include <bits/stdc++.h>
using namespace std;
struct node {
  long long x;
  bool s;
  node(long long a, bool b) { x = a, s = b; }
};
bool operator<(node a, node b) { return a.x > b.x; }
priority_queue<node> pq;
int main() {
  int n;
  long long temp;
  cin >> n;
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    cin >> temp;
    if (pq.empty() || pq.top().x > temp) {
      pq.push(node(temp, 0));
    } else {
      long long now = pq.top().x;
      bool se = pq.top().s;
      pq.pop();
      if (se) pq.push(node(now, 0));
      ans += temp - now, pq.push(node(temp, 1));
    }
  }
  cout << ans << endl;
  return 0;
}
