#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16777216")
using namespace std;
long long A[5001], B[5001], dp[5001];
int n, m;
long long iabs(long long a) {
  if (a < 0) return (-a);
  return a;
}
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> A[i];
    B[i] = A[i];
  }
  sort(B, B + n);
  m = 0;
  for (int i = 0; i < n; i++) {
    while (i + 1 < n && B[i] == B[i + 1]) i++;
    B[m++] = B[i];
  }
  dp[0] = iabs(A[0] - B[0]);
  for (int j = 1; j < m; j++) dp[j] = min(dp[j - 1], abs(A[0] - B[j]));
  for (int i = 1; i < n; i++) {
    dp[0] += abs(A[i] - B[0]);
    for (int j = 1; j < m; j++)
      dp[j] = min(dp[j - 1], dp[j] + abs(A[i] - B[j]));
  }
  cout << dp[m - 1] << endl;
  return 0;
}
