#include <bits/stdc++.h>
using namespace std;
int N;
long long a[5000], b[5000];
int num[5000];
int ord[5000];
int main() {
  scanf("%d", &N);
  for (int Ni = 0; Ni < N; Ni++) {
    int p;
    scanf("%d", &p);
    num[Ni] = ord[Ni] = p;
  }
  sort(ord, ord + N);
  a[0] = abs(num[0] - ord[0]);
  for (int Nj = 1; Nj < N; Nj++) {
    a[Nj] = min(a[Nj - 1], (long long)abs(num[0] - ord[Nj]));
  }
  for (int Ni = 1; Ni < N; Ni++) {
    b[0] = a[0] + abs(num[Ni] - ord[0]);
    for (int Nj = 1; Nj < N; Nj++) {
      b[Nj] = min(b[Nj - 1], a[Nj] + abs(num[Ni] - ord[Nj]));
    }
    for (int Nj = 0; Nj < N; Nj++) a[Nj] = b[Nj];
  }
  printf("%I64d\n", a[N - 1]);
}
