#include <bits/stdc++.h>
using namespace std;
const long long oo = (1LL << 60);
int A[5010], T[5010];
long long dp[2][5010];
int n;
int main() {
  ios_base::sync_with_stdio(false);
  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> A[i];
    T[i] = A[i];
  }
  sort(T, T + n);
  memset(dp, -1, sizeof(dp));
  long long ou = oo, best = oo;
  for (int i = 0; i < n; ++i) {
    best = oo;
    for (int j = 0; j < n; ++j) {
      long long &res = dp[i & 1][j];
      best = i == 0 ? 0 : min(dp[(i - 1) & 1][j], best);
      res = best + abs(T[j] - A[i]);
      if (i == n - 1) ou = min(ou, res);
    }
  }
  cout << ou << endl;
  return 0;
}
