n = int(input())
a_list = list(map(int, input().split()))

a_set = set(a_list)
a_dict = {a:[] for a in a_set}
p_dict = {}
for position, activity in enumerate(a_list):
  a_dict[activity].append(position+1)
  p_dict[position+1] = activity

# print(a_list)
# print(a_dict)
# print(p_dict)

sorted_a = sorted(set(a_list), reverse=True)

l, r = 1, n
after_p_dict = {}
after_a_dict = {}
ret = 0
for sa in sorted_a:
#   print(100, l, r)
  
  p_list = sorted(a_dict[sa])
  l_dist_list = [(l-_p)**2 for _p in p_list]
  r_dist_list = [(r-_p)**2 for _p in p_list]
  inner_l, inner_r = 0, len(p_list)-1
  for i in range(len(p_list)):
    if l_dist_list[inner_l] >= r_dist_list[inner_r]:
      p = p_list[inner_l]
      inner_l += 1
    else:
      p = p_list[inner_r]
      inner_r -= 1
      
    if (l-p)**2 >= (r-p)**2:
      after_a_dict[sa] = l
      ret += abs(l-p)*sa
#       print(111, 'sa: {}, p→l: {}→{}, diff: {}'.format(sa, p,l, abs(l-p)*sa))
      l += 1
    else:
#       print(222, 'sa: {}, p→r: {}→{}, diff: {}'.format(sa, p, r, abs(r-p)*sa))
      after_a_dict[sa] = r
      ret += abs(r-p)*sa
      r -= 1
  
#     print(200, l, r)
#     if l > r:
#       print('end!')

print(ret)