#include <bits/stdc++.h>
using namespace std;
inline void read(int &data) {
  data = 0;
  int e = 1;
  char ch = getchar();
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') e = -1, ch = getchar();
  while (ch >= '0' && ch <= '9') data = data * 10 + ch - 48, ch = getchar();
  data *= e;
}
inline void read(long long &data) {
  data = 0;
  int e = 1;
  char ch = getchar();
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') e = -1, ch = getchar();
  while (ch >= '0' && ch <= '9') data = data * 10 + ch - 48, ch = getchar();
  data *= e;
}
inline void write(int data) {
  if (data < 0) data = -data, putchar('-');
  if (data > 9) write(data / 10);
  putchar(data % 10 + 48);
}
inline void write(long long data) {
  if (data < 0) data = -data, putchar('-');
  if (data > 9) write(data / 10);
  putchar(data % 10 + 48);
}
bool cmp(int a, int b) { return a < b; }
priority_queue<long long, vector<long long>, greater<long long> > q;
long long n, x, ans = 0;
int main() {
  read(n);
  for (int i = 1; i <= n; ++i) {
    read(x);
    if (q.empty() || q.top() > x)
      q.push(x);
    else {
      ans += x - q.top();
      q.pop();
      q.push(x), q.push(x);
    }
  }
  write(ans), puts("");
}
