#include <bits/stdc++.h>
using namespace std;
long double const EPS = 1e-7;
long long const INF = 1e18;
vector<long long> minn(5050);
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n;
  cin >> n;
  vector<long long> a, b;
  for (long long i = 0; i < n; i++) {
    long long x;
    cin >> x;
    a.push_back(x);
    b.push_back(x);
  }
  sort(b.begin(), b.end());
  for (long long i = 0; i < n; i++) {
    vector<long long> temp(n);
    for (long long j = 0; j < n; j++) {
      long long dp;
      dp = minn[j] + abs(a[i] - b[j]);
      temp[j] = min((j - 1 >= 0 ? temp[j - 1] : INF), dp);
    }
    minn = temp;
  }
  cout << minn[n - 1];
  return 0;
}
