#include <bits/stdc++.h>
using namespace std;
const long long int mod = 1000000007;
const double pi = acos(-1.0);
string str[] = {"YES", "NO"};
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long int n, a, b, c, d, e, x, y,
      mul = 1, cn = 0, cn1 = 0, cn2 = 0, sm = 0, sm1 = 0, sm2 = 0, mx = INT_MIN,
      mx1 = INT_MIN, mn = INT_MAX, mn1 = INT_MAX, i, j, k = 0, temp;
  string s, ss, sss, str = "";
  set<long long int> st;
  map<long long int, long long int> mp;
  bool f = true, ff = true;
  cin >> a;
  long long int ar[a];
  for (int i = 0; i < a; i++) {
    cin >> ar[i];
    if (ar[i] > mx) mx = ar[i], cn = i;
  }
  for (int i = 1; i < cn; i++) {
    cn1 += abs(ar[i] - ar[0]);
  }
  for (int i = cn; i < a; i++) {
    cn1 += abs(ar[i] - mx);
  }
  for (int i = 0; i < a; i++) {
    sm += abs(ar[i] - ar[0]);
    sm1 += abs(ar[i] - mx);
  }
  cout << min(sm, min(sm1, cn1)) << endl;
  return 0;
}
