def solve(area): if len(area) <= 1: return 0 selected_ind = [0] * len(area) max_ind = area.index(max(area)) min_ind = max_ind for i in reversed(range(max_ind)): if area[min_ind] > area[i]: min_ind = i selected_ind[min_ind] = 1 min_ind = max_ind for i in range(max_ind+1, len(area)): if area[min_ind] > area[i]: min_ind = i selected_ind[min_ind] = 1 count = sum(selected_ind) tmp_sum = sum(selected_ind[0:max_ind]) tmp_len = len(selected_ind[0:max_ind]) if tmp_len == tmp_sum and tmp_len > 2: count += int(tmp_sum * (tmp_sum - 1) / 2) else: next_left_ind = max_ind if next_left_ind > 0: while area.index(max(area[0:next_left_ind])) == (next_left_ind - 1): count += sum(selected_ind[0:next_left_ind - 1]) next_left_ind -= 1 if next_left_ind < 1: break count += solve(area[0:next_left_ind]) tmp_sum = sum(selected_ind[max_ind + 1: len(area)]) tmp_len = len(selected_ind[max_ind + 1: len(area)]) if tmp_len == tmp_sum and tmp_len > 2: count += int(tmp_sum * (tmp_sum - 1) / 2) else: next_right_ind = max_ind if next_right_ind < len(area) - 1: while area.index(max(area[next_right_ind + 1: len(area)])) == 0: count += sum(selected_ind[next_right_ind + 2: len(area)]) next_right_ind += 1 if next_right_ind > len(area) - 1: break count += solve(area[next_right_ind + 1: len(area)]) return int(count) N = int(input()) data = input().split() Input = [int(s) for s in data] print(solve(Input))