#include <bits/stdc++.h>
using namespace std;
long long int memo[5005];
int a[5005], b[5005];
int main() {
  int n;
  int i, j;
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    b[i] = a[i];
  }
  sort(b, b + n);
  long long int mn;
  for (i = 0; i < n; i++) {
    mn = 1e13;
    for (j = 0; j < n; j++) {
      mn = (mn < memo[j] ? mn : memo[j]);
      memo[j] = mn + abs(a[i] - b[j]);
    }
  }
  mn = 1e13;
  for (i = 0; i < n; i++) {
    mn = (mn < memo[i] ? mn : memo[i]);
  }
  cout << mn << endl;
}
