#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
using ld = long double;
using P = pair<int, int>;
using vs = vector<string>;
using vi = vector<int>;
using vvi = vector<vi>;
template <class T>
using PQ = priority_queue<T>;
template <class T>
using PQG = priority_queue<T, vector<T>, greater<T> >;
const int INF = 100010001;
const ll LINF = (ll)INF * INF * 10;
template <typename T1, typename T2>
inline bool chmax(T1 &a, T2 b) {
  return a < b && (a = b, true);
}
template <typename T1, typename T2>
inline bool chmin(T1 &a, T2 b) {
  return a > b && (a = b, true);
}
template <typename T1, typename T2>
istream &operator>>(istream &is, pair<T1, T2> &p) {
  return is >> p.first >> p.second;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
  return os << p.first << ' ' << p.second;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  vi a(n);
  for (int i = 0; i < n; ++i) cin >> a[i];
  multimap<int, int> mp;
  for (int i = 0; i < n; ++i) mp.emplace(a[i], i);
  ll l = 0, r = 0;
  int i = 0;
  for (auto itr = mp.begin(); itr != mp.end(); itr++) {
    l += ll(itr->first) * abs(itr->second - i++);
  }
  vector<multimap<int, int>::iterator> num;
  for (auto itr = mp.end(); itr != mp.begin();) {
    itr = prev(itr);
    int l_ = 0, r_ = 0;
    num.push_back(itr);
    i = num.size() - 1;
    int cnt = 0;
    for (auto it = mp.begin(); it != mp.end(); it++) {
      if (i != -1 and it == num[i]) {
        r_ += ll(it->first) * abs(it->second - i--);
      } else {
        l_ += ll(it->first) * abs(it->second - int(num.size()) - cnt++);
      }
    }
    if (l + r > l_ + r_) {
      num.pop_back();
    } else {
      l = l_;
      r = r_;
    }
  }
  cout << l + r << endl;
}
