#include <bits/stdc++.h>
using namespace std;
long long dp[2][5005];
vector<long long> a;
vector<long long> b;
long long x, n;
int main() {
  ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> x;
    a.push_back(x);
    b.push_back(x);
  }
  sort(b.begin(), b.end());
  dp[0][0] = abs(a[0] - b[0]);
  for (int i = 1; i < n; i++) {
    dp[0][i] = min(dp[0][i - 1], abs(a[0] - b[i]));
  }
  for (int i = 1; i < n; i++) {
    dp[i % 2][0] = dp[(i % 2) ^ 1][0] + abs(a[i] - b[0]);
    for (int o = 1; o < n; o++) {
      dp[i % 2][o] =
          min(dp[i % 2][o - 1], dp[(i % 2) ^ 1][o] + abs(a[i] - b[o]));
    }
  }
  cout << dp[(n - 1) % 2][n - 1] << endl;
}
