#include <bits/stdc++.h>
using namespace std;
void solve();
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  solve();
  return 0;
}
void solve() {
  int n;
  cin >> n;
  vector<int> a(n);
  for (int i = 0; i < n; ++i) cin >> a[i];
  vector<int> idx(n);
  iota(idx.begin(), idx.end(), 0);
  sort(idx.begin(), idx.end(), [&](int i1, int i2) { return a[i1] < a[i2]; });
  vector<vector<long long>> dp(2, vector<long long>(n));
  for (int i = n - 1; i >= 0; --i) {
    dp[1][i] = max(0, a[idx[i]] - a[n - 1]);
  }
  for (int j = n - 2; j >= 0; --j) {
    dp[0][n - 1] = dp[1][n - 1] + a[idx[n - 1]] - a[j];
    for (int i = n - 2; i >= 0; --i) {
      dp[0][i] = min(dp[0][i + 1], abs(a[j] - a[idx[i]]) + dp[1][i]);
    }
    dp[0].swap(dp[1]);
  }
  cout << *min_element(dp[1].begin(), dp[1].end()) << endl;
}
