#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:32000000")
void initf() {}
using namespace std;
const int inf = (1 << 30);
long long dp[2][5005];
long long a[5005], b[5005];
int n;
long long mabs(long long x) { return (x < 0 ? (-x) : (x)); }
void solve() {
  scanf("%d", &n);
  if (n == 1) {
    cout << "0\n";
    return;
  }
  for (int i = 0; i < (n); ++i) {
    scanf("%lld", a + i);
    b[i] = a[i];
  }
  sort(b, b + n);
  int N = 1;
  for (int i = 0; i < (n); ++i)
    if (i)
      if (b[i] != b[i - 1]) b[N++] = b[i];
  dp[0][0] = mabs(b[0] - a[0]);
  for (int j = (1); j <= (N - 1); ++j)
    dp[0][j] = min(dp[0][j - 1], mabs(b[j] - a[0]));
  for (int i = (1); i <= (n - 1); ++i) {
    for (int j = 0; j < (N); ++j) {
      if (j == 0)
        dp[1][j] = mabs(b[0] - a[i]) + dp[0][j];
      else
        dp[1][j] = min(dp[1][j - 1], dp[0][j] + mabs(a[i] - b[j]));
    }
    for (int j = 0; j < (N); ++j) dp[0][j] = dp[1][j];
  }
  cout << dp[0][N - 1] << endl;
}
int main() {
  initf();
  solve();
  return (0);
}
