#include <bits/stdc++.h>
using namespace std;
void boost() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
const int N = 1e6;
const long long inf = 1e9 + 7;
const long double PI = acos(-1);
long long bin_pow(long long x, long long y) {
  long long res = 1, base = x;
  while (y) {
    if (y & 1) {
      res *= base;
    }
    base *= base;
    y /= 2;
  }
  return res;
}
int n;
long long a[5005], ans, b[5005], dp[3][5005];
int main() {
  boost();
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    b[i] = a[i];
  }
  sort(b + 1, b + 1 + n);
  for (int j = 0; j <= n; j++) {
    dp[1][j] = inf * inf;
    dp[2][j] = inf * inf;
  }
  ans = inf * inf;
  for (int i = 1; i <= n; i++) {
    dp[1][i] = min(dp[1][i], abs(a[1] - b[i]));
    dp[1][i] = min(dp[1][i], dp[1][i - 1]);
  }
  for (int i = 2; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      long long cur = min(dp[1][j] + abs(a[i] - b[j]), dp[2][j - 1]);
      dp[2][j] = min(dp[2][j], cur);
    }
    for (int j = 0; j <= n; j++) {
      dp[1][j] = dp[2][j];
      dp[2][j] = inf * inf;
    }
  }
  for (int i = 1; i <= n; i++) {
    ans = min(dp[1][i], ans);
  }
  cout << ans;
}
