#include <bits/stdc++.h>
using namespace std;
int n, nums[5005], sorted[5005];
long long dp[5005];
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> nums[i];
    sorted[i] = nums[i];
  }
  sort(sorted + 1, sorted + n + 1);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++) {
      dp[j] = dp[j] + abs(nums[i] - sorted[j]);
      if (j > 1) dp[j] = min(dp[j], dp[j - 1]);
    }
  cout << dp[n] << '\n';
  return 0;
}
