#include <bits/stdc++.h>
using namespace std;
const int N = 5001;
long long a[N], mem[N][2], b[N];
int n, m;
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    b[i] = a[i];
  }
  sort(b, b + n);
  m = unique(b, b + n) - b;
  for (int i = n - 1; i >= 0; i--)
    mem[i][1 - m & 1] =
        abs(a[i] - b[m - 1]) + ((i + 1 < n) ? mem[i + 1][1 - m & 1] : 0ll);
  for (int j = m - 2; j >= 0; j--)
    for (int i = n - 1; i >= 0; i--)
      mem[i][j & 1] =
          min(mem[i][1 - j & 1],
              abs(a[i] - b[j]) + ((i + 1 < n) ? mem[i + 1][j & 1] : 0ll));
  long long ans = 1ll << 50;
  ans = min(mem[0][0], mem[0][1]);
  cout << ans << endl;
  return 0;
}
