#include <bits/stdc++.h>
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, -1, 0, 1};
using namespace std;
int n, m;
int a[5010], b[5010], c[5010];
void init() {
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) {
    scanf("%d", &a[i]);
    b[i] = a[i];
  }
  sort(b, b + n);
  m = 0;
  for (int i = 0; i < n; ++i)
    if (i == 0 || b[i] != b[i - 1]) c[m++] = b[i];
}
long long min(long long a, long long b) { return a < b ? a : b; }
long long f[2][5001];
void dp() {
  memset(f, 0, sizeof(f));
  f[0][0] = abs(a[0] - c[0]);
  for (int i = 1; i < m; ++i) f[0][i] = min(f[0][i - 1], abs(a[0] - c[i]));
  for (int i = 1; i < n; ++i) {
    f[i % 2][0] = f[1 - i % 2][0] + abs(a[i] - c[0]);
    for (int j = 1; j < m; ++j)
      f[i % 2][j] = min(f[i % 2][j - 1], f[1 - i % 2][j] + abs(a[i] - c[j]));
  }
  long long ans = f[(n - 1) % 2][0];
  for (int i = 1; i < m; ++i)
    if (f[(n - 1) % 2][i] < ans) ans = f[(n - 1) % 2][i];
  cout << ans << endl;
}
int main() {
  init();
  dp();
  return 0;
}
