#include <bits/stdc++.h>
using namespace std;
long long n, a[5005], ind[5005], dp[3][5005], minim = 100000000000000000;
int abs(int a) {
  if (a > 0) return a;
  return -a;
}
bool cmp(int x, int y) { return a[x] < a[y]; }
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i], ind[i] = i;
  sort(ind + 1, ind + n + 1, cmp);
  for (int i = 1; i <= n; i++) dp[i % 2][0] = 100000000000000000;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++) {
      dp[i % 2][j] = dp[(i - 1) % 2][j] + abs(a[i] - a[ind[j]]);
      dp[i % 2][j] = min(dp[i % 2][j], dp[i % 2][j - 1]);
    }
  for (int j = 1; j <= n; j++) minim = min(minim, dp[n % 2][j]);
  cout << minim;
  return 0;
}
