#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pii = pair<ll, ll>;
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  ll N;
  cin >> N;
  vector<ll> A(N);
  for (ll i = 0; i < N; i++) cin >> A[i];
  priority_queue<pii> q;
  for (ll i = 0; i < N; i++) q.push({A[i], i});
  ll l = 0, r = N - 1;
  vector<ll> sum(N + 1);
  for (ll i = 0; i < N; i++) sum[i + 1] = sum[i] + A[i];
  ll ans = 0;
  for (ll i = 0; i < N; i++) {
    ll c = q.top().first;
    ll x = q.top().second;
    q.pop();
    if (sum[x] > c && sum[x] > sum[N] - sum[x + 1]) {
      ans += abs(x - l) * c;
      l++;
    } else if (sum[N] - sum[x + 1] > c && sum[x] < sum[N] - sum[x + 1]) {
      ans += abs(x - r) * c;
      r--;
    } else if (sum[x] > sum[N] - sum[x + 1]) {
      ans += abs(x - l) * c;
      l++;
    } else if (sum[x] < sum[N] - sum[x + 1]) {
      ans += abs(x - r) * c;
      r--;
    } else {
      if (N % 2 == 0) {
        ans += abs(x - l) * c;
        l++;
      } else {
        if (sum[x] < sum[N] - sum[x + 1]) {
          ans += abs(x - r) * c;
          r--;
        } else {
          ans += abs(x - l) * c;
          l++;
        }
      }
    }
  }
  cout << ans << "\n";
  return 0;
}
