#include <bits/stdc++.h>
using namespace std;
const int maxn = 593910;
long long a[maxn];
namespace FAST_IO {
template <typename T>
void read(T &a) {
  a = 0;
  long long f = 1;
  char c = getchar();
  while (!isdigit(c)) {
    if (c == '-') {
      f = -1;
    }
    c = getchar();
  }
  while (isdigit(c)) {
    a *= 10;
    a += c - '0';
    c = getchar();
  }
  a = a * f;
}
template <typename T>
void write(T a) {
  if (a < 0) {
    a = -a;
    putchar('-');
  }
  if (a > 9) {
    write(a / 10);
  }
  putchar(a % 10 + '0');
}
template <typename T>
void writeln(T) {
  write(a);
  puts("");
}
}  // namespace FAST_IO
long long ans, ans1;
priority_queue<long long> big;
priority_queue<long long, vector<long long>, greater<long long> > small;
signed main() {
  long long n;
  FAST_IO::read(n);
  for (long long i = 1; i <= n; i++) {
    FAST_IO::read(a[i]);
  }
  for (long long i = 1; i <= n; i++) {
    big.push(a[i]);
    if (a[i] < big.top()) {
      ans += big.top() - a[i];
      big.pop();
      big.push(a[i]);
    }
  }
  cout << ans;
}
