#include <bits/stdc++.h>
using namespace std;
const int maxn = 5002;
int n;
long long a[maxn], b[maxn];
long long f[2][maxn];
template <typename T>
inline T abs(const T x) {
  return x < 0 ? -x : x;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%lld", &a[i]), b[i] = a[i];
  sort(b + 1, b + n + 1);
  f[1][1] = abs(a[1] - b[1]);
  for (int i = 2; i <= n; ++i) f[1][i] = min(f[1][i - 1], abs(a[1] - b[i]));
  for (int i = 2; i <= n; ++i) {
    int cur = i & 1, last = cur ^ 1;
    f[cur][1] = abs(a[i] - b[1]) + f[last][1];
    for (int j = 2; j <= n; ++j)
      f[cur][j] = min(f[cur][j - 1], f[last][j] + abs(a[i] - b[j]));
  }
  printf("%lld\n", *min_element(f[n & 1] + 1, f[n & 1] + n + 1));
  return 0;
}
