#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
using PL = pair<long long, long long>;
const int INF = 1001001007;
const int MOD = 1000000007;
template <typename T>
void printvec(vector<T> &ar) {
  for (int i = 0; i < (ar.size() - 1); ++i) cout << ar[i] << " ";
  cout << ar[ar.size() - 1] << endl;
}
template <typename Q>
void printvvec(vector<vector<Q>> &ar) {
  for (int i = 0; i < (ar.size()); ++i) {
    for (int j = 0; j < (ar[0].size() - 1); ++j) cout << ar[i][j] << " ";
    cout << ar[i][ar[0].size() - 1] << endl;
  }
}
template <typename S>
bool range(S a, S b, S x) {
  return (a <= x && x < b);
}
int main() {
  int n;
  cin >> n;
  vector<PL> ar(n);
  ll kei = 0;
  for (int i = 0; i < (n); ++i) {
    cin >> ar[i].first;
    ar[i].second = i;
    kei += ar[i].first;
  }
  vector<ll> rui(n + 1, 0);
  for (int i = 0; i < (n); ++i) rui[i + 1] = rui[i] + ar[i].first;
  sort(ar.begin(), ar.end());
  int le = 0;
  int ri = n - 1;
  vector<ll> an(n);
  ll ans = 0;
  for (int i = 0; i < (n); ++i) {
    if (rui[ar[n - 1 - i].second] > kei - rui[ar[n - 1 - i].second + 1]) {
      ans += ar[n - 1 - i].first * (ar[n - 1 - i].second - le);
      le++;
    } else {
      ans += ar[n - 1 - i].first * (ri - ar[n - 1 - i].second);
      ri--;
    }
  }
  cout << ans << endl;
}
