module M = Map.Make (struct type t = int * int let compare = compare end)

let () =
    let split s =
        let rec loop i cur flag acc =
            if i = String.length s then ( if flag then cur :: acc else acc) else ( match flag, s.[i] with
                | true,  ' ' -> loop (i + 1) "" false (cur :: acc)
                | false, ' ' -> loop (i + 1) "" false acc
                | true,  v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
                | false, v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
            )
        in
        List.map int_of_string (List.rev (loop 0 "" false []))
    in
    let main () =
        let n = int_of_string (read_line ()) in
        let p = Array.of_list (split (read_line ())) in
        let rec loop i map acc =
            if i = n then acc else
                let next = M.fold (fun ((first, second) as org) v next ->
                    let key = if p.(i) > first then p.(i), first else
                        if p.(i) > second then first, p.(i) else org
                    in
                    M.add key (v + try M.find key next with _ -> 0) next) map M.empty
                in
                let acc = acc + M.fold (fun (_, sec) v acc -> sec * v + acc) next 0 in
                loop (i + 1) (M.add (p.(i), 0) 1 next) acc
        in
        let r = loop 1 (M.singleton (p.(0), 0) 1) 0 in
        Printf.printf "%d\n" r
    in
    main ()