#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 5005;
ll a[N], b[N], dp[N];
int main() {
  ll n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> 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++)
      if (j == 1)
        dp[j] += abs(b[j] - a[i]);
      else
        dp[j] = min(dp[j - 1], dp[j] + abs(b[j] - a[i]));
  cout << dp[n];
}
