#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const double eps = 1e-8;
long long dp[2][5005];
long long a[5005];
long long b[5005];
int n, k;
int main() {
  ios_base::sync_with_stdio(false);
  vector<long long> tp;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    tp.push_back(a[i]);
  }
  sort(tp.begin(), tp.end());
  tp.resize(unique(tp.begin(), tp.end()) - tp.begin());
  k = tp.size();
  for (int i = 1; i <= k; i++) b[i] = tp[i - 1];
  dp[1][1] = abs(a[1] - b[1]);
  for (int j = 2; j <= k; j++) dp[1][j] = min(abs(a[1] - b[j]), dp[1][j - 1]);
  for (int i = 2; i <= n; i++) {
    dp[i & 1][1] = abs(a[i] - b[1]) + dp[(i - 1) & 1][1];
    for (int j = 2; j <= k; j++)
      dp[i & 1][j] =
          min(dp[i & 1][j - 1], dp[(i - 1) & 1][j] + abs(a[i] - b[j]));
  }
  cout << dp[n & 1][k] << endl;
  return 0;
}
