#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);
  for (int i = 0; i < N; i++) cin >> a[i];
  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) {
    long long left_potential = 0, right_potential = 0;
    for (int i = left_bound; i < child.second; i++) {
      if (a[i] <= child.first) left_potential += a[i];
    }
    for (int i = child.second + 1; i <= right_bound; i++) {
      if (a[i] < child.first) right_potential += a[i];
    }
    if (left_potential > right_potential && left_potential > child.first) {
      ans += abs(child.second - left_bound) * child.first;
      left_bound++;
    } else if (right_potential >= left_potential &&
               right_potential > child.first) {
      ans += abs(child.second - right_bound) * child.first;
      right_bound--;
    } else {
      if (abs(child.second - left_bound) > abs(child.second - right_bound)) {
        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;
}
