#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
const int N = 5e3 + 5;
int n, a[N], b[N];
long long dp[2][N];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 0; i < n; i++) cin >> a[i], b[i] = a[i];
  sort(b, b + n);
  dp[0][n] = dp[1][n] = 1e14;
  for (int i = n - 1; i >= 0; i--)
    for (int j = n - 1; j >= 0; j--)
      dp[i & 1][j] =
          min(dp[(i & 1) ^ 1][j] + abs(a[i] - b[j]), dp[i & 1][j + 1]);
  cout << dp[0][0];
  return 0;
}
