#include <bits/stdc++.h>
using namespace std;
const int N = 5010;
long long a[N], b[N];
long long dp[2][N];
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
    b[i] = a[i];
  }
  sort(b, b + n);
  dp[0][0] = abs(a[0] - b[0]);
  for (int j = 1; j < n; j++) {
    dp[0][j] = min(abs(a[0] - b[j]), dp[0][j - 1]);
  }
  for (int i = 1; i < n; i++) {
    int dir = i & 1;
    dp[dir][0] = abs(a[i] - b[0]) + dp[dir ^ 1][0];
    for (int j = 1; j < n; j++) {
      dp[dir][j] = min(dp[dir][j - 1], dp[dir ^ 1][j] + abs(a[i] - b[j]));
    }
  }
  printf("%lld\n", dp[(n - 1) & 1][n - 1]);
}
