#include <bits/stdc++.h>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
using namespace std;
inline int get() {
  int n;
  char c;
  while ((c = getchar()) || 23333) {
    if (c == '-') goto s;
    if (c >= '0' && c <= '9') break;
  }
  n = c - '0';
  while ((c = getchar()) || 23333) {
    if (c >= '0' && c <= '9')
      n = n * 10 + c - '0';
    else
      return (n);
  }
s:
  while ((c = getchar()) || 23333) {
    if (c >= '0' && c <= '9')
      n = n * 10 - c + '0';
    else
      return (n);
  }
}
int ints[300001];
typedef struct _n {
  int me;
  int you;
  _n(int a, int b) {
    me = a;
    you = b;
  }
  friend bool operator<(const _n &a, const _n &b) {
    return (ints[a.you] > ints[b.you]);
  }
} node;
priority_queue<node> que;
int pointat[300001];
int main() {
  int n = get();
  for (register int i = 1; i <= n; i++) ints[i] = get(), pointat[i] = i;
  long long ans = 0;
  for (register int i = 1; i <= n; i++) {
    if (que.empty()) {
      que.push(_n(i, i));
      continue;
    }
    if (ints[que.top().you] >= ints[i]) {
      que.push(_n(i, i));
      continue;
    }
    ans += (long long)ints[i] - ints[que.top().you];
    node cjr = que.top();
    que.pop();
    if (cjr.me != cjr.you)
      pointat[cjr.you] = cjr.you, que.push(_n(cjr.you, cjr.you));
    pointat[i] = cjr.me;
    pointat[cjr.me] = 0;
    que.push(_n(cjr.me, i));
  }
  cout << ans << endl;
  return (0);
}
