#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 5005;
int n, A[MAX_N];
set<int> diff;
int ind_to_val[MAX_N];
map<int, int> val_to_ind;
long long W[2][MAX_N];
long long absll(long long x) {
  if (x < 0) {
    return -x;
  }
  return x;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> A[i];
    diff.insert(A[i]);
  }
  int nr = 0;
  for (set<int>::iterator it = diff.begin(); it != diff.end(); it++) {
    nr++;
    ind_to_val[nr] = *it;
    val_to_ind[*it] = nr;
  }
  for (int i = 1; i <= n; i++) {
    W[1][i] = absll(A[1] - ind_to_val[i]);
    if (i > 1) {
      W[1][i] = min(W[1][i], W[1][i - 1]);
    }
  }
  for (int i = 2; i <= n; i++) {
    for (int j = 1; j <= nr; j++) {
      W[i % 2][j] = W[(i + 1) % 2][j] + absll(A[i] - ind_to_val[j]);
      if (j > 1) {
        W[i % 2][j] = min(W[i % 2][j], W[i % 2][j - 1]);
      }
    }
  }
  long long result = W[n % 2][1];
  for (int i = 2; i <= nr; i++) {
    result = min(result, W[n % 2][i]);
  }
  cout << result;
  return 0;
}
