#include <bits/stdc++.h>
using namespace std;
int n, a[5555], s[5555];
long long F[5555], G[5555], *f = F, *g = G;
int main() {
  cin >> n;
  for (int i = 0; i < n; ++i) cin >> a[i], s[i] = a[i];
  sort(s, s + n);
  for (int i = 0; i < n; ++i) {
    g[0] = f[0] + abs(s[0] - a[i]);
    for (int j = 1; j < n; ++j) g[j] = min(g[j - 1], f[j] + abs(a[i] - s[j]));
    swap(f, g);
  }
  cout << *min_element(f, f + n) << endl;
  return 0;
}
