#include <bits/stdc++.h>
using namespace std;
const long long INF = 1000 * 1000 * 1000LL * 1000 * 1000 * 1000, N = 5010;
long long a[N], b[N], d[N];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n;
  long long x;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    b[i] = a[i];
  }
  sort(b, b + n);
  for (int i = 0; i < n; i++) d[i] = abs(a[0] - b[i]);
  for (int i = 1; i < n; i++) {
    x = INF;
    for (int j = 0; j < n; j++) {
      x = min(x, d[j]);
      d[j] = x + abs(a[i] - b[j]);
    }
  }
  x = INF;
  for (int i = 0; i < n; i++) x = min(x, d[i]);
  cout << x;
}
