#include <bits/stdc++.h>
using namespace std;
const int N = 5001;
int n;
long long memo[2][N];
long long vs[N];
vector<long long> arr;
long long oo = 100000000000000000LL;
long long solve(int idx, int f) {
  if (idx == n) return 0;
  long long ret = memo[idx][f];
  if (ret != -1) return ret;
  ret = oo;
  if (f + 1 < n) ret = min(ret, solve(idx, f + 1));
  ret = min(ret, (solve(idx + 1, f) + abs(vs[idx] - arr[f])));
  return memo[idx][f] = ret;
}
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> vs[i];
    arr.push_back(vs[i]);
  }
  sort(arr.begin(), arr.end());
  for (int i = 0; i < n; i++) memo[n % 2][i] = 0;
  for (int i = n - 1; i >= 0; i--) {
    for (int j = n - 1; j >= 0; j--) {
      long long ret = oo;
      if (j + 1 < n) ret = min(ret, memo[i % 2][j + 1]);
      ret = min(ret, memo[(i + 1) % 2][j] + abs(vs[i] - arr[j]));
      memo[i % 2][j] = ret;
    }
  }
  cout << memo[0][0] << '\n';
  return 0;
}
