//#pragma GCC optimize("O3")
#include<bits/stdc++.h>
#define ll long long int
#define ld long double
#define pb push_back
#define mp make_pair
#define mod 1000000007
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);
#define all(x) x.begin(),x.end()
#define F first
#define S second
#define fo(i,n) for(int i=0;i<(n);i++)
#define inp(a) int a;cin>>a;
#define inpa(a,n)vector<int> a(n);fo(i,n)cin>>a[i];
#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n";
using namespace std;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define OSET_TYPE long long
#define oset tree<OSET_TYPE, null_type, less<OSET_TYPE>, rb_tree_tag, tree_order_statistics_node_update>
// find_by_order(k): to iterator to kth element
// order_of_key(k) : number of items strictly smaller than k


#define int ll
// #define MAX 20
#define INF (int)1e18

template<class T> ostream& operator<<(ostream& cout,vector<T> V)
{cout<<"[ ";for(auto v:V)cout<<v<<' ';return cout<<']';}
template<class L,class R> ostream& operator<<(ostream& cout,pair<L, R> P)
{return cout<<'('<<P.F<<','<< P.S<<')';}

int solve1(int n,vector<int> a)
{
	vector<int> left,right;
	fo(i,n)
	{
		int less=0;
		int ct=0;
		for(int j:left)
		{
			if(a[j]<a[i])
				less+=a[j];
			else if(a[i]>a[j])
				ct++;
		}
		int prol=a[i]*(i-ct)-less;
		
		
		less=0;
		ct=0;
		for(int j:right)
		{
			if(a[j]<a[i])
				less+=a[j];
			else if(a[i]>a[j])
				ct++;
		}
		int pror=a[i]*(n-i-1-ct)-less;
		
		if(pror>prol)
		{
			right.pb(i);
		}
		else
		{
			left.pb(i);
		}
	}
	
	vector<pair<int,int>> b,c;
	for(int i:left)
		b.pb({a[i],i});
	for(int i:right)
		c.pb({a[i],i});
	
	sort(all(b));
	sort(all(c));
	reverse(all(b));
	reverse(all(c));
	
	// cerr<<b<<'\n';
	// cerr<<c<<'\n';
	
	swap(b,c);
	
	int ans=0;
	fo(i,b.size())
	{
		ans+=b[i].F*abs(n-i-1-b[i].S);
	}
	fo(i,c.size())
	{
		ans+=c[i].F*abs(c[i].S-i);
	}
	
	return ans;
}


// int solve2(int n,vector<int> a)
// {
// 	return 0;
// 	int n2=n/2;
// 	int n1=n-n2;
// 	vector<pair<int,int>> b(n1),c(n2);
// 	fo(i,n1)
// 		b[i]={a[i],i};
// 	fo(i,n2)
// 		c[i]={a[i+n1],n1+i};
	
// 	sort(all(b));
// 	sort(all(c));
// 	reverse(all(b));
// 	reverse(all(c));
	
// 	int ans=0;
// 	fo(i,n1)
// 	{
// 		ans+=b[i].F*abs(n-i-1-b[i].S);
// 	}
// 	fo(i,n2)
// 	{
// 		ans+=c[i].F*abs(c[i].S-i);
// 	}
// 	return ans;
// }

signed main()
{
	fio
	inp(n)
	inpa(a,n)
	
	
	
	cout<<solve1(n,a)<<'\n';
	printclock;
}