#include <bits/stdc++.h>
using namespace std;
const long long inf = 2000000000000000001;
int n;
long long dp[2][5010], A[5010], V[5010];
inline long long absv(long long x) { return (x >= 0) ? x : -x; }
inline long long mn(long long x, long long y) {
  if (x < y) return x;
  return y;
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%lld", &A[i]);
    V[i] = A[i];
  }
  sort(V, V + n);
  for (int i = 0; i < n; i++) dp[0][i] = inf;
  bool sel = 1;
  for (int i = 0; i < n; i++) {
    dp[sel][0] = mn(absv(A[0] - V[i]), dp[1 - sel][0]);
    for (int j = 1; j < n; j++)
      dp[sel][j] = mn(dp[1 - sel][j], dp[sel][j - 1] + absv(A[j] - V[i]));
    sel = 1 - sel;
  }
  printf("%lld\n", dp[1 - sel][n - 1]);
}
