#include <bits/stdc++.h>
using namespace std;
const int maxn = 5005;
const long long inf = 1LL << 61;
long long dp[2][maxn];
int a[maxn], b[maxn];
int n;
void solve() {
  memcpy(b, a, sizeof(b));
  sort(b, b + n);
  int p = 0, q = 1;
  for (int i = 0; i < n; ++i) dp[0][i] = dp[1][i] = inf;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      if (i == 0) {
        dp[q][j] = abs(a[i] - b[j]);
        if (j) dp[q][j] = min(dp[q][j], dp[q][j - 1]);
      } else if (j == 0) {
        dp[q][j] = dp[p][j] + abs(a[i] - b[j]);
      } else {
        dp[q][j] = min(dp[q][j - 1], dp[p][j] + abs(a[i] - b[j]));
      }
    }
    swap(p, q);
  }
  long long ans = inf;
  for (int j = 0; j < n; ++j) ans = min(ans, dp[p][j]);
  printf("%I64d\n", ans);
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) {
    scanf("%d", &a[i]);
  }
  solve();
  return 0;
}
