#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  vector<long long> arr(n);
  set<long long> distinctVal;
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
    distinctVal.insert(arr[i]);
  }
  vector<long long> b(distinctVal.begin(), distinctVal.end());
  vector<vector<long long> > dp(2, vector<long long>(b.size()));
  dp[0][0] = abs(arr[0] - b[0]);
  for (int i = 1; i < b.size(); i++) {
    dp[0][i] = min(dp[0][i - 1], abs(arr[0] - b[i]));
  }
  for (int i = 1; i < n; i++) {
    int row = i % 2;
    dp[row][0] = dp[1 - row][0] + abs(arr[i] - b[0]);
    for (int j = 1; j < b.size(); j++) {
      dp[row][j] = min(dp[row][j - 1], dp[1 - row][j] + abs(arr[i] - b[j]));
    }
  }
  cout << dp[(n - 1) % 2][b.size() - 1] << endl;
}
