#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-5;
long long llinf = 1e18 + 10;
int intinf = 1e9 + 7;
const long long mod = 1e9 + 7;
const int N = 5003;
int n;
long long a[N];
long long v[N];
long long dp[2][N];
int main() {
  scanf("%d", &(n));
  for (int i = 0; i < int(n); ++i) scanf("%lld", &(a[i])), v[i] = a[i];
  sort(v, v + n);
  for (int j = 0; j < int(n); ++j)
    dp[0][j] = min(abs(a[0] - v[j]), j ? dp[0][j - 1] : llinf);
  for (int i = 1; i < n; i++) {
    for (int j = 0; j < int(n); ++j) {
      dp[i & 1][j] = min(j ? dp[i & 1][j - 1] : llinf,
                         dp[(i - 1) & 1][j] + abs(v[j] - a[i]));
    }
  }
  cout << dp[(n - 1) & 1][(n - 1)] << endl;
  return 0;
}
