#include <bits/stdc++.h>
using namespace std;
long long climbTheHill(vector<int> slope) {
  vector<int> tmp2(slope);
  sort(tmp2.begin(), tmp2.end());
  vector<int> sorted_slope;
  sorted_slope.push_back(tmp2[0]);
  for (int i = 1; i < tmp2.size(); i++) {
    if (tmp2[i] != tmp2[i - 1]) sorted_slope.push_back(tmp2[i]);
  }
  vector<long long> tmp(sorted_slope.size(), 0);
  vector<vector<long long>> dp(slope.size(), tmp);
  dp[0][0] = abs(slope[0] - sorted_slope[0]);
  for (int i = 1; i < slope.size(); i++) {
    dp[i][0] = abs(slope[i] - sorted_slope[0]) + dp[i - 1][0];
  }
  for (int j = 1; j < sorted_slope.size(); j++) {
    dp[0][j] = min(abs(slope[0] - (long long)sorted_slope[j]), dp[0][j - 1]);
  }
  for (int i = 1; i < slope.size(); i++) {
    for (int j = 1; j < sorted_slope.size(); j++) {
      dp[i][j] =
          min(dp[i - 1][j] + abs(slope[i] - sorted_slope[j]), dp[i][j - 1]);
    }
  }
  return dp[slope.size() - 1][sorted_slope.size() - 1];
}
long long climbTheHill1(vector<int> slope) {
  vector<int> tmp2(slope);
  sort(tmp2.begin(), tmp2.end());
  vector<int> sorted_slope;
  sorted_slope.push_back(tmp2[0]);
  for (int i = 1; i < tmp2.size(); i++) {
    if (tmp2[i] != tmp2[i - 1]) sorted_slope.push_back(tmp2[i]);
  }
  vector<long long> dp1(sorted_slope.size(), 0);
  dp1[0] = abs(slope[0] - sorted_slope[0]);
  for (int j = 1; j < sorted_slope.size(); j++) {
    dp1[j] = min(abs(slope[0] - (long long)sorted_slope[j]), dp1[j - 1]);
  }
  for (int i = 1; i < slope.size(); i++) {
    vector<long long> dp2;
    for (int j = 0; j < sorted_slope.size(); j++) {
      if (j == 0)
        dp2.push_back(abs(slope[i] - sorted_slope[0]) + dp1[0]);
      else
        dp2.push_back(
            min(dp1[j] + abs(slope[i] - sorted_slope[j]), dp2[j - 1]));
    }
    dp1 = dp2;
  }
  return dp1[sorted_slope.size() - 1];
}
int main(int argc, const char* argv[]) {
  int n;
  cin >> n;
  vector<int> slope(n, 0);
  for (int i = 0; i < n; i++) {
    cin >> slope[i];
  }
  cout << climbTheHill1(slope) << endl;
  return 0;
}
