#include <bits/stdc++.h>
using namespace std;
void llSort(long long d[], int s) {
  int i, j;
  long long k, t;
  if (s <= 1) return;
  k = (d[0] + d[s - 1]) / 2;
  i = -1;
  j = s;
  for (;;) {
    while (d[++i] < k)
      ;
    while (d[--j] > k)
      ;
    if (i >= j) break;
    t = d[i];
    d[i] = d[j];
    d[j] = t;
  }
  llSort(d, i);
  llSort(d + j + 1, s - j - 1);
}
int main() {
  int i, j, k, l, m, n, ok;
  long long in[6000], dp[6000], num[6000], add;
  long long res = 100000000000000000LL;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> k;
    in[i] = num[i] = k;
  }
  llSort(num, n);
  dp[0] = 0;
  for (i = 0; i < n; i++) dp[i + 1] = 100000000000000000LL;
  for (k = 0; k < n; k++) {
    for (i = 0; i < n; i++) {
      if (in[i] >= num[k])
        add = in[i] - num[k];
      else
        add = num[k] - in[i];
      if (dp[i + 1] > dp[i] + add) dp[i + 1] = dp[i] + add;
    }
  }
  cout << dp[n] << endl;
  return 0;
}
