#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
int a[5555];
int vals[5555];
int n;
long long d[2][5555];
int main() {
  scanf("%d", &n);
  for (int i = 0, _n = (n); i < _n; i++) {
    scanf("%d", &a[i]);
    vals[i] = a[i];
  }
  sort(vals, vals + n);
  memset(d, 0, sizeof d);
  ;
  int cur = 0, nw = 1;
  for (int i = 0, _n = (n); i < _n; i++) {
    for (int j = 0, _n = (n); j < _n; j++) {
      d[nw][j] = d[cur][j] + abs(a[i] - vals[j]);
      if (j > 0) d[nw][j] = min(d[nw][j], d[nw][j - 1]);
    }
    swap(cur, nw);
  }
  long long res = d[cur][0];
  for (int i = 0, _n = (n); i < _n; i++) res = min(res, d[cur][i]);
  printf("%lld\n", res);
  return 0;
}
