// Arup Guha
// 2/7/2022
// Solution to 2022 January USACO Silver Problem: Cow Frisbee

import java.util.*;
import java.io.*;

public class cowfrisbee {
	
	public static void main(String[] args) throws Exception {
	
		BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(stdin.readLine());
		item[] list = new item[n];
		StringTokenizer tok = new StringTokenizer(stdin.readLine());
		
		// Get values and sort (storing original indexes).
		for (int i=0; i<n; i++) {
			int val = Integer.parseInt(tok.nextToken());
			list[i] = new item(val, i);
		}
		Arrays.sort(list);
		
		// Set up a tree set of indexes.
		TreeSet<Integer> set = new TreeSet<Integer>();
		long res = 0;
		
		// Insert each item from highest to lowest.
		for (int i=0; i<n; i++) {
			
			// Location of current value.
			int cur = list[i].i;
			
			// Who this person looks up to next.
			Integer up = set.higher(cur);
			Integer down = set.lower(cur);
			
			// If there's someone, we add the distance to them.
			if (up != null) res = res + (up-cur+1);
			if (down != null) res = res + (cur-down+1);
			
			// Now this index is in the set too.
			set.add(cur);
		}
		
		// Ta da!
		System.out.println(res);
	}
}

class item implements Comparable<item> {

	public int x;
	public int i;
	
	public item(int val, int idx) {
		x = val;
		i = idx;
	}
	
	public int compareTo(item other) {
		if (this.x != other.x) return other.x-this.x;
		return this.i - other.i;
	}
}