#include <bits/stdc++.h>
using namespace std;
struct Node {
  long long value, l, r;
  Node(){};
  Node(long long v, long long left, long long right) {
    value = v;
    l = left;
    r = right;
  }
};
vector<Node> nodes;
struct cmp {
  bool operator()(const int a, const int b) const {
    return nodes[a].value < nodes[b].value;
  }
};
void del(int x) {
  nodes[nodes[x].l].r = nodes[x].r;
  nodes[nodes[x].r].l = nodes[x].l;
}
void A() {
  int n;
  cin >> n;
  int k = n / 3;
  for (int i = 0; i < n; i++) {
    long long x;
    cin >> x;
    nodes.emplace_back(x, (i - 1 + n) % n, (i + 1) % n);
  }
  priority_queue<int, vector<int>, cmp> que;
  for (int i = 0; i < n; i++) {
    que.push(i);
  }
  int cnt = 0;
  vector<bool> vis(n, 0);
  long long res = 0;
  while (cnt < k) {
    int id = que.top();
    que.pop();
    if (vis[id]) continue;
    cnt++;
    res += (nodes[id].value);
    int pre = nodes[id].l;
    int next = nodes[id].r;
    vis[pre] = vis[next] = 1;
    nodes[id].value = (nodes[pre].value + nodes[next].value - nodes[id].value);
    que.push(id);
    del(pre);
    del(next);
  }
  cout << res << endl;
}
void B() {
  int n;
  cin >> n;
  long long res = 0;
  vector<long long> a(n, 0);
  for (int i = 0; i < n; i++) cin >> a[i];
  priority_queue<long long, vector<long long>, greater<long long>> que;
  for (int i = 0; i < n; i++) {
    que.push(a[i]);
    if (!que.empty() && que.top() < a[i]) {
      res += a[i] - que.top();
      que.pop();
      que.push(a[i]);
    }
  }
  cout << res << endl;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  B();
  return 0;
}
