#[allow(unused_imports)]
use std::cmp::Ordering;

#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};

#[allow(unused_imports)]
use std::iter::FromIterator;

#[allow(unused_macros)]
macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::min($x, min!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::max($x, max!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! get {
    ([$t: ty]) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            line.split_whitespace().map(|t|t.parse::<$t>().unwrap()).collect::<Vec<_>>()
        }
    };
    ([$t: ty];$n: expr) => {
        (0..$n).map(|_|get!([$t])).collect::<Vec<_>>()
    };
    ($t: ty) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t: ty),*) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            ($(iter.next().unwrap().parse::<$t>().unwrap(),)*)
        }
    };
    ($t: ty; $n: expr) => {
        (0..$n).map(|_|get!($t)).collect::<Vec<_>>()
    };
    ($($t: ty),*; $n: expr) => {
        (0..$n).map(|_|get!($($t),*)).collect::<Vec<_>>()
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        #[cfg(debug_assertions)]
        writeln!(&mut std::io::stderr(), concat!("[DEBUG] ", $(stringify!($a), "={:?} "),*), $($a),*).unwrap();
    }
}

const BIG_STACK_SIZE: bool = true;

#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}

pub trait Monoid<T>: SemiGroup<T> {
    fn identity() -> T;
}
pub trait SemiGroup<T>: Magma<T> {}
pub trait Magma<T> {
    fn operate(lhs: T, rhs: T) -> T;
}
#[derive(Debug)]
struct SegmentTree<T, U> {
    len: usize,
    nodes: Vec<T>,
    phantom: std::marker::PhantomData<U>,
}
impl<T, U> SegmentTree<T, U>
where
    U: Monoid<T>,
    T: Copy + Clone + std::fmt::Debug,
{
    #[allow(dead_code)]
    fn new(n: usize) -> Self {
        let mut len = 1;
        while len < n {
            len *= 2;
        }
        SegmentTree {
            len: len,
            nodes: vec![U::identity(); 2 * len - 1],
            phantom: Default::default(),
        }
    }
    #[allow(dead_code)]
    fn from_vec(vec: &Vec<T>) -> Self {
        let mut len = 1;
        while len < vec.len() {
            len *= 2;
        }
        let mut nodes = vec![U::identity(); 2 * len - 1];
        for i in 0..vec.len() {
            nodes[i + len - 1] = vec[i];
        }
        for i in (0..len - 1).rev() {
            nodes[i] = U::operate(nodes[2 * i + 1], nodes[2 * i + 2]);
        }
        SegmentTree {
            len: len,
            nodes: nodes,
            phantom: Default::default(),
        }
    }
    #[allow(dead_code)]
    fn update(&mut self, index: usize, val: T) {
        let mut index = index;
        index += self.len - 1;
        self.nodes[index] = val;
        while index > 0 {
            index = (index - 1) / 2;
            self.nodes[index] = U::operate(self.nodes[2 * index + 1], self.nodes[2 * index + 2]);
        }
    }
    fn get(&self, l: usize, r: usize) -> T {
        self._get(l, r, 0, 0, self.len)
    }
    fn _get(&self, ql: usize, qr: usize, index: usize, l: usize, r: usize) -> T {
        if r <= ql || qr <= l {
            return U::identity();
        }
        if ql <= l && r <= qr {
            return self.nodes[index];
        }
        let vl = self._get(ql, qr, 2 * index + 1, l, (l + r) / 2);
        let vr = self._get(ql, qr, 2 * index + 2, (l + r) / 2, r);
        U::operate(vl, vr)
    }
}

struct IMonoidMax;
impl Monoid<usize> for IMonoidMax {
    fn identity() -> usize {
        0
    }
}
impl Magma<usize> for IMonoidMax {
    fn operate(lhs: usize, rhs: usize) -> usize {
        max!(lhs, rhs)
    }
}
impl SemiGroup<usize> for IMonoidMax {}

struct IMonoidMin;
impl Monoid<usize> for IMonoidMin {
    fn identity() -> usize {
        std::usize::MAX
    }
}
impl Magma<usize> for IMonoidMin {
    fn operate(lhs: usize, rhs: usize) -> usize {
        min!(lhs, rhs)
    }
}
impl SemiGroup<usize> for IMonoidMin {}

fn solve() {
    let n = get!(usize);
    let p = get!([usize]);

    let mut ltree = SegmentTree::<usize, IMonoidMax>::new(n + 2);
    let mut rtree = SegmentTree::<usize, IMonoidMin>::new(n + 2);
    ltree.update(0, 0);
    rtree.update(n + 1, n + 1);

    let mut vec = vec![0; n + 1];
    for i in 0..n {
        vec[p[i]] = i + 1;
    }

    let mut res = 0usize;
    for i in (1..n + 1).rev() {
        let v = vec[i];
        let l1 = ltree.get(0, v);
        let r1 = rtree.get(v + 1, n + 2);

        if l1 > 0 {
            let l2 = ltree.get(0, l1);
            res += i * (l1 - l2) * (r1 - v);
        }
        if r1 < n + 1 {
            let r2 = rtree.get(r1 + 1, n + 2);
            res += i * (r2 - r1) * (v - l1);
        }

        ltree.update(v, v);
        rtree.update(v, v);
    }
    println!("{}", res);
}


Measured memory_bytes: 14716