#include <bits/stdc++.h>
using namespace std;
long long a[10000], b[10000];
long long dp[10000], f[10000];
long long mabs(long long x) {
  if (x < 0)
    return -x;
  else
    return x;
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%lld", &a[i]), b[i] = a[i];
  sort(b + 1, b + 1 + n);
  int h = 1;
  for (int i = 2; i <= n; i++) {
    if (b[i] != b[h]) b[++h] = b[i];
  }
  for (int i = 1; i <= n; i++) {
    long long minx = f[1];
    for (int j = 1; j <= h; j++) {
      minx = min(minx, f[j]);
      dp[j] = minx + mabs(b[j] - a[i]);
      f[j] = dp[j];
    }
  }
  long long ans = dp[1];
  for (int i = 1; i <= h; i++) ans = min(ans, dp[i]);
  printf("%lld\n", ans);
  return 0;
}
