#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  register long long x = 0, w = 1;
  register char ch = getchar();
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') {
    ch = getchar();
    w = -1;
  }
  while (ch >= '0' && ch <= '9') {
    x = (x << 3) + (x << 1) + (ch ^ 48);
    ch = getchar();
  }
  return x * w;
}
long long min(long long x, long long y) { return x < y ? x : y; }
const long long M = 5e4 + 10;
const long long inf = 1e17 + 5;
long long n, a[M], f[2][M], rk[M];
signed main() {
  n = read();
  for (long long i = 1; i <= n; ++i) {
    a[i] = read();
    rk[i] = a[i];
  }
  sort(rk + 1, rk + n + 1);
  long long cnt = unique(rk + 1, rk + n + 1) - rk - 1;
  for (long long i = 1; i <= n; ++i) {
    a[i] = lower_bound(rk + 1, rk + cnt + 1, a[i]) - rk;
  }
  for (long long i = 0; i <= cnt; ++i) f[0][i] = f[1][i] = inf;
  f[0][0] = 0;
  for (long long i = 1; i <= n; ++i) {
    long long k = f[!(i & 1)][0];
    for (long long j = 0; j <= cnt; ++j) {
      k = min(k, f[!(i & 1)][j]);
      f[i & 1][j] = k + abs(rk[a[i]] - rk[j]);
    }
    f[i & 1][0] = inf;
  }
  long long ans = inf;
  for (long long i = 1; i <= cnt; ++i) ans = min(ans, f[n & 1][i]);
  cout << ans;
  return 0;
}
