#include <bits/stdc++.h>
using namespace std;
int main() {
  int i, j, k, l, m, n, ok;
  long long in[5001], dp[5001], num[5001], add;
  long long res = 100000000000000000LL;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> k;
    in[i] = num[i] = k;
  }
  sort(num, num + n);
  dp[0] = 0;
  for (i = 0; i < n; i++) dp[i + 1] = 100000000000000000LL;
  for (k = 0; k < n; k++) {
    for (i = 0; i < n; i++) {
      if (in[i] >= num[k])
        add = in[i] - num[k];
      else
        add = num[k] - in[i];
      if (dp[i + 1] > dp[i] + add) dp[i + 1] = dp[i] + add;
    }
  }
  cout << dp[n] << endl;
  return 0;
}
