#include <bits/stdc++.h>
using namespace std;
long long read() {
  long long t = 0, f = 1;
  char c = getchar();
  while (!isdigit(c)) f = c ^ 45, c = getchar();
  while (isdigit(c)) t = (t << 1) + (t << 3) + (c ^ 48), c = getchar();
  return f ? t : -t;
}
const long long N = 5021, inf = 1e18;
long long n, m, a[N], f[N], dp[2][N];
int main() {
  n = read();
  for (int i = 1; i <= n; ++i) f[i] = a[i] = read();
  sort(f + 1, f + 1 + n), m = unique(f + 1, f + 1 + n) - f - 1;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      dp[i & 1][j] = min(j == 1 ? inf : dp[i & 1][j - 1],
                         dp[i - 1 & 1][j] + abs(a[i] - f[j]));
  printf("%lld", dp[n & 1][m]);
  return 0;
}
