#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
struct SegmentTree {
 private:
  int n;
  vector<long long> node;

 public:
  SegmentTree(vector<long long> v) {
    int sz = v.size();
    n = 1;
    while (n < sz) n *= 2;
    node.resize(2 * n - 1, 0);
    for (int i = 0; i < (sz); i++) {
      node[i + n - 1] = v[i];
    }
    for (int i = n - 2; i >= 0; i--) {
      node[i] = node[2 * i + 1] + node[2 * i + 2];
    }
  }
  void update(long long x, long long val) {
    x += n - 1;
    node[x] = val;
    while (x != 0) {
      x = (x - 1) / 2;
      node[x] = node[x * 2 + 1] + node[x * 2 + 2];
    }
  }
  int get(long long a, long long b, int k = 0, int l = 0, int r = -1) {
    if (a > b) return 0;
    if (r < 0) r = n;
    if (r <= a || b <= l) return 0;
    if (a <= l && r <= b) return node[k];
    int vl = get(a, b, 2 * k + 1, l, (l + r) / 2);
    int vr = get(a, b, 2 * k + 2, (l + r) / 2, r);
    return vl + vr;
  }
};
int main() {
  int n;
  cin >> n;
  vector<pair<long long, int>> vec;
  vector<long long> sg;
  for (int i = 0; i < (n); i++) {
    long long tmp;
    cin >> tmp;
    sg.push_back(tmp);
    vec.push_back(make_pair(tmp, i));
  }
  SegmentTree st(sg);
  sort(vec.begin(), vec.end());
  reverse(vec.begin(), vec.end());
  long long ans = 0;
  long long l = 0, r = n - 1;
  vector<long long> res(n);
  for (auto v : vec) {
    if (v.first * (abs(r - v.second)) - st.get(l, v.second) >
        v.first * (abs(v.second - l)) - st.get(v.second + 1, r + 1)) {
      ans += v.first * abs(r - v.second);
      st.update(v.second, 0);
      res[r] = v.first;
      r--;
    } else {
      ans += v.first * abs(v.second - l);
      st.update(v.second, 0);
      res[l] = v.first;
      l++;
    }
  }
  cout << ans << endl;
  return 0;
}
