#include <bits/stdc++.h>
using namespace std;
inline int Read() {
  long long s = 0, w = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') w = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    s = (s << 3) + (s << 1) + (ch ^ 48);
    ch = getchar();
  }
  return s * w;
}
const int MX = 100010;
long long dp[MX], a[MX], b[MX], N;
void init() {
  N = Read();
  for (int i = 1; i <= N; ++i) a[i] = Read(), b[i] = a[i];
}
void solve() {
  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(a[i] - b[j]);
      else
        dp[j] = min(dp[j - 1], dp[j] + abs(a[i] - b[j]));
    }
  printf("%lld\n", dp[N]);
}
int main() {
  init();
  solve();
  return 0;
}
