#include <bits/stdc++.h>
using namespace std;
int a[5100], b[5100];
long long c[5100];
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    b[i] = a[i];
  }
  sort(b, b + n);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) {
      int d = b[j] - a[i];
      if (d > 0)
        c[j] = min(c[j - 1], d + c[j]);
      else
        c[j] -= d;
    }
  long long ans = c[0];
  while (--n)
    if (ans > c[n]) ans = c[n];
  cout << ans << endl;
}
