from collections import defaultdict
n=int(input())
A=[int(i) for i in input().split()]
#A=[1,10,2,4,3,9,5,7]
#A=[8,6,9,1,2,1]
peak=[]

keep = A[0]

def f(A):
    idx=defaultdict(list)
    for i,a in enumerate(A):
        idx[a].append(i)
    return idx
def calc(ida,idb,aa):
    dist = 0
    for i in aa:
        l1 = ida[i]
        l2 = idb[i]
        l1.sort()
        l2.sort()
        m1 = sum([abs(i-j) for i,j in zip(l1,l2[::-1])])
        m2 = sum([abs(i-j) for i,j in zip(l1[::-1],l2)])
        #print(i,max(m1,m2)*i)
        dist+=max(m1,m2)*i
    return dist

for i in range(1,len(A)):
    if keep>A[i]:
        l = A[:i-1]
        r = A[i-1:]
        l.sort()
        r.sort(reverse=True)
        #print(r,l)
        r.extend(l)
        peak.append(r)
        l = A[:i]
        r = A[i:]
        l.sort()
        r.sort(reverse=True)
        #print(r,l)
        r.extend(l)
        peak.append(r)
    keep = A[i]

if len(peak) == 0:
    if len(A)%2==0:
        yy = len(A)//2
        B=A[yy:][::-1]
        B.extend(A[:yy]
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        print(cal)
    else:
        yy = len(A)//2 + 1
        B=A[yy:][::-1]
        B.extend(A[:yy])
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        print(cal)
else:
    ans = 0
    for B in peak:
        aa = set(A)
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        ans = max(ans,cal)
    print(ans)