#include <bits/stdc++.h>
using namespace std;
int n, v[300050];
long long ans;
struct node {
  int v, sz, w;
  node *l, *r;
  node(int x) {
    v = x, sz = 1, w = rand();
    l = r = NULL;
  }
};
node *root = NULL;
int tam(node *root) { return root != NULL ? root->sz : 0; }
void upd(node *&root) {
  if (root == NULL) return;
  root->sz = tam(root->l) + tam(root->r) + 1;
}
void Merge(node *&root, node *l, node *r) {
  if (l == NULL) {
    root = r;
    return;
  }
  if (r == NULL) {
    root = l;
    return;
  }
  if (l->w > r->w) {
    Merge(l->r, l->r, r);
    root = l;
  } else {
    Merge(r->l, l, r->l);
    root = r;
  }
  upd(root);
}
bool used[300050];
void Split(node *root, node *&l, node *&r, int idx) {
  if (!root)
    l = r = NULL;
  else {
    int p = tam(root->l) + 1;
    if (p < idx) {
      Split(root->r, root->r, r, idx - p);
      l = root;
    } else {
      Split(root->l, l, root->l, idx);
      r = root;
    }
  }
  upd(root);
}
void insert(node *&root, int val) {
  if (!root)
    root = new node(val);
  else {
    if (val > root->v)
      insert(root->r, val);
    else
      insert(root->l, val);
  }
  upd(root);
}
void Remove(node *&root, int val) {
  if (root->v == val)
    Merge(root, root->l, root->r);
  else if (root->v > val)
    Remove(root->l, val);
  else
    Remove(root->r, val);
  upd(root);
}
int buscaMenor(node *root) {
  if (!root) return 2000000000;
  if (!root->l) return root->v;
  return buscaMenor(root->l);
}
multiset<int> ss;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n;
  for (int i = 1, x; i <= n; i++) {
    cin >> x;
    if (!ss.size())
      ss.insert(x);
    else {
      int v = *ss.begin();
      if (v <= x) {
        ans += (long long)x - (long long)v;
        ss.erase(ss.begin());
        ss.insert(x);
        ss.insert(x);
      } else
        ss.insert(x);
    }
  }
  cout << ans << "\n";
}
