#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5005;
int a[MAXN], b[MAXN], n, m;
long long DP[MAXN];
int main() {
  scanf("%d", &n);
  int i, j;
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    b[i] = a[i];
  }
  sort(b, b + n);
  m = n;
  i = 0, j = 0;
  while (i < m) {
    while (j < m && b[j] == b[i]) j++;
    if (j - i > 1) {
      memmove(b + i + 1, b + j, (m - j) * sizeof(int));
      m -= (j - i - 1);
    }
    i++;
    j = i;
  }
  memset(DP, 0, sizeof(DP));
  for (i = 0; i < n; i++)
    for (j = 0; j < m; j++) {
      DP[j] += abs(a[i] - b[j]);
      if (j > 0 && DP[j] > DP[j - 1]) DP[j] = DP[j - 1];
    }
  printf("%I64d\n", DP[m - 1]);
  return 0;
}
