#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  scanf("%d", &(n));
  static long long a[int(5e3 + 5)];
  set<int> s;
  for (int i = 1, __R = n; i <= __R; i++) {
    scanf("%lld", &(a[i]));
    s.insert(a[i]);
  }
  static long long b[int(5e3 + 5)], k = 0;
  for (long long x : s) b[++k] = x;
  static long long dp[2][int(5e3 + 5)];
  int lst = 0, cur = 1;
  dp[lst][1] = abs(a[1] - b[1]);
  for (int j = 2, __R = k; j <= __R; j++)
    dp[lst][j] = min(dp[lst][j - 1], abs(a[1] - b[j]));
  for (int i = 2, __R = n; i <= __R; i++) {
    dp[cur][1] = dp[lst][1] + abs(a[i] - b[1]);
    for (int j = 2, __R = k; j <= __R; j++)
      dp[cur][j] = min(dp[cur][j - 1], dp[lst][j] + abs(a[i] - b[j]));
    swap(lst, cur);
  }
  cout << dp[lst][k] << endl;
  return 0;
}
