#include <bits/stdc++.h>
using namespace std;
long long a[5050], b[5050], f[5050];
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%I64d", a + i);
    b[i] = a[i];
  }
  sort(b + 1, b + 1 + n);
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= n; ++j) {
      f[j] += abs(a[i] - b[j]);
      if (j > 1) f[j] = min(f[j], f[j - 1]);
    }
  }
  printf("%I64d\n", f[n]);
}
