#include <bits/stdc++.h>
using namespace std;
const int N = 100 * 1000;
int n;
long long dp[2][N];
int c[N], a[N];
bool read() {
  if (!(cin >> n)) return false;
  for (int i = 0; i < int(n); ++i) {
    cin >> a[i];
    c[i] = a[i];
  }
  return true;
}
void upd(long long &a, long long b) {
  if (a == -1) a = b;
  a = min(a, b);
}
void solve() {
  int t = 0;
  sort(c, c + n);
  memset(dp, -1, sizeof dp);
  dp[t][0] = 0;
  for (int i = 0; i < int(n); ++i) {
    memset(dp[!t], -1, sizeof(dp[!t]));
    long long mn = -1;
    for (int j = 0; j < int(n); ++j) {
      if (dp[t][j] != -1) upd(mn, dp[t][j]);
      upd(dp[!t][j], mn + abs(a[i] - c[j]));
    }
    t = !t;
  }
  long long res = -1;
  for (int i = 0; i < int(n); ++i)
    if (dp[t][i] != -1) upd(res, dp[t][i]);
  cout << res << endl;
}
int main() {
  while (read()) solve();
  return 0;
}
