using System; using static System.Console; using System.Linq; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; class Program { static int NN => int.Parse(ReadLine()); static int[] NList => ReadLine().Split().Select(int.Parse).ToArray(); public static void Main() { Solve(); } static void Solve() { var n = NN; var p = NList; var ans = Ita(n, p); Array.Reverse(p); ans += Ita(n, p); WriteLine(ans); } static long Ita(int n, int[] p) { var largelist = new List(); var lpos = new List(); var smalllist = new List(); var spos = new List(); var ans = 0L; for (var i = n - 1; i >= 0; --i) { while (largelist.Count > 0 && largelist[^1] < p[i]) { largelist.RemoveAt(largelist.Count - 1); lpos.RemoveAt(lpos.Count - 1); } largelist.Add(p[i]); lpos.Add(i); while (smalllist.Count > 0 && smalllist[^1] > p[i]) { smalllist.RemoveAt(smalllist.Count - 1); spos.RemoveAt(spos.Count - 1); } smalllist.Add(p[i]); spos.Add(i); if (spos.Count == 1) { ans += lpos.Count - 1; // WriteLine($"{i}: {lpos.Count - 1}"); } else { var pos = LowerBoundDesc(spos[^2], lpos); ans += lpos.Count - 2 - pos; } } return ans; } static int LowerBoundDesc(int min, IList list) { if (list[list.Count - 1] >= min) return list.Count - 1; var ng = list.Count; var ok = -1; while (ng - ok > 1) { var mid = (ok + ng) / 2; if (list[mid] < min) ng = mid; else ok = mid; } return ok; } }