#include <bits/stdc++.h>
using namespace std;
long long a[5010], b[5010], n, dp[5010];
int main() {
  cin >> n;
  for (long long i = 1ll; i <= n; i++) scanf("%I64d", &a[i]), b[i] = a[i];
  sort(b + 1ll, b + n + 1ll);
  dp[0ll] = (long long)1000000000000000007;
  for (long long i = 1ll; i <= n; i++) {
    for (long long j = 1ll; j <= n; j++) {
      dp[j] = min(dp[j - 1ll], dp[j] + abs(b[j] - a[i]));
    }
  }
  cout << dp[n] << endl;
  return 0;
}
