#include <bits/stdc++.h>
using namespace std;
long long n, in[5100], st[5100], f[5100], ans = 9999999999999;
signed main() {
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> in[i];
  }
  memset(f, 0x7f, sizeof(f));
  memcpy(st, in, sizeof(in));
  sort(st + 1, st + n + 1);
  for (long long i = 1; i <= n; i++) f[i] = 0;
  for (long long i = 1; i <= n; i++) {
    for (long long o = 1; o <= n; o++) {
      f[o] = min(f[o - 1], f[o] + abs(in[i] - st[o]));
    }
  }
  for (long long i = 1; i <= n; i++) {
    ans = min(ans, f[i]);
  }
  cout << ans;
}
