#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
const long long MOD = 998244353;
const long long MX = 1000001;
int N;
long long ans = 0;
void solve() {
  cin >> N;
  int left_bound = 0, right_bound = N - 1;
  vector<long long> a(N), psum(N), ssum(N);
  for (int i = 0; i < N; i++) cin >> a[i];
  psum[0] = a[0];
  ssum[N - 1] = a[N - 1];
  for (int i = 1; i < N; i++) psum[i] = psum[i - 1] + a[i];
  for (int i = N - 2; i >= 0; i--) ssum[i] = ssum[i + 1] + a[i];
  vector<bool> avail(N, true);
  vector<pair<long long, long long> > children;
  for (int i = 0; i < N; i++) children.push_back({a[i], i});
  sort(children.begin(), children.end(),
       greater<pair<long long, long long> >());
  for (auto& child : children) {
    if (psum[child.second] > ssum[child.second]) {
      ans += abs(child.second - left_bound) * child.first;
      left_bound++;
    } else {
      ans += abs(child.second - right_bound) * child.first;
      right_bound--;
    }
  }
  cout << ans;
}
int main() {
  cin.sync_with_stdio(0);
  cin.tie(0);
  long long T;
  T = 1;
  while (T--) solve();
  return 0;
}
