#include <bits/stdc++.h>
using namespace std;
int a[5005];
int vals[5005];
int n;
long long d[2][5005];
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    vals[i] = a[i];
  }
  sort(vals, vals + n);
  memset(d, 0, sizeof(d));
  int cur = 0, nw = 1;
  for (int i = 0; i < n; i++) {
    for (int j = 0; 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; i < n; i++) {
    res = min(res, d[cur][i]);
  }
  cout << res << endl;
  return 0;
}
