#include <bits/stdc++.h>
using namespace std;
long long f[5005];
int a[5005], b[5005];
int main() {
  int n;
  while (scanf("%d", &n) != EOF) {
    for (int i = 0; i <= n; i++) f[i] = 0;
    for (int i = 1; i <= n; i++) {
      scanf("%d", &a[i]);
      b[i] = a[i];
    }
    sort(b + 1, b + 1 + n);
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= n; j++) {
        f[j] += abs(a[i] - b[j]);
        if (j > 1) f[j] = min(f[j - 1], f[j]);
      }
    cout << f[n] << endl;
  }
  return 0;
}
