#include <bits/stdc++.h>
using namespace std;
int main() {
  int no_of_elements;
  cin >> no_of_elements;
  vector<long long> sorted_A(no_of_elements + 1), A(no_of_elements + 1);
  for (int i = 1; i <= no_of_elements; i++) {
    cin >> A[i];
    sorted_A[i] = A[i];
  }
  sort(sorted_A.begin() + 1, sorted_A.end());
  const long long oo = 1e18;
  vector<long long> minimum_steps(no_of_elements + 1);
  for (int j = 1; j <= no_of_elements; j++) {
    for (int i = 1; i <= no_of_elements; i++) {
      if (i == 1) {
        minimum_steps[i] =
            (j == 1 ? abs(A[i] - sorted_A[j])
                    : min(minimum_steps[i], abs(A[i] - sorted_A[j])));
      } else if (j == 1) {
        minimum_steps[i] = minimum_steps[i - 1] + abs(A[i] - sorted_A[j]);
      } else {
        minimum_steps[i] = min(minimum_steps[i],
                               minimum_steps[i - 1] + abs(A[i] - sorted_A[j]));
      }
    }
  }
  cout << minimum_steps[no_of_elements] << "\n";
  return 0;
}
