#include <bits/stdc++.h>
int n;
long long a[5005], dp[2][5005], f[2][5005], b[5005];
long long labs(long long x) { return (x > 0) ? x : (-x); }
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%I64d", a + i);
    b[i] = a[i];
  }
  f[0][0] = f[1][0] = 0x3f3f3f3f3f3f3f3f;
  std::sort(b + 1, b + n + 1);
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= n; ++j) {
      dp[i & 1][j] = f[(i - 1) & 1][j] + labs(b[j] - a[i]);
      f[i & 1][j] = std::min(f[i & 1][j - 1], dp[i & 1][j]);
    }
  }
  printf("%I64d\n", f[n & 1][n]);
  return 0;
}
