#include <bits/stdc++.h>
using namespace std;
long long a[10000];
long long d[2][10000], mn[2][10000];
int main() {
  int n;
  cin >> n;
  vector<long long> b;
  for (int i = (int)(0); i < (int)(n); i++) {
    cin >> a[i];
    b.push_back(a[i]);
  }
  sort(b.begin(), b.end());
  for (int i = (int)(0); i < (int)(n); i++) d[0][i] = abs(a[0] - b[i]);
  mn[0][0] = d[0][0];
  for (int i = (int)(1); i < (int)(n); i++)
    mn[0][i] = min(mn[0][i - 1], d[0][i]);
  for (int i = (int)(1); i < (int)(n); i++) {
    for (int j = (int)(0); j < (int)(n); j++)
      d[i & 1][j] = mn[1 - (i & 1)][j] + abs(a[i] - b[j]);
    mn[i & 1][0] = d[i & 1][0];
    for (int j = (int)(1); j < (int)(n); j++)
      mn[i & 1][j] = min(mn[i & 1][j - 1], d[i & 1][j]);
  }
  cout << mn[1 - (n & 1)][n - 1];
  return 0;
}
