This page is still under construction.

Parts of this page are still being built. What you see may change.

Dominating Duos

Interview

Time limit4sMemory limit512 MB

Summary
Count pairs (i, j) in a permutation where both endpoints exceed every element strictly between them, with n up to 10^6.
Level

Medium6 of 10

Topics
Stack, Array, Combinatorics
Solved
No attempts yet

Problem

A group of people are standing in a line. Each person has a distinct height. You would like to count the number of unordered pairs of people in the line such that they are taller than everyone in between them in the line.

More formally, let dd be a sequence of the heights of the people in order from left to right. We want to count the number of pairs of indices ii and jj with i<ji < j such that for all kk with i<k<ji < k < j, di>dkd_i > d_k and dj>dkd_j > d_k. Note that if j=i+1j = i + 1 (i.e., there are no kk's between ii and jj), it is trivially true.

Input

The first line of input contains an integer nn (2≤n≤1062 \le n \le 10^6), which is the number of people.

Each of the next nn lines contains a single integer did_i (1≤di≤n1 \le d_i \le n). These are the heights of the people in the group, in the order in which they're standing. The sequence is guaranteed to be a permutation of the integers 11 through nn.

Output

Output a single integer, which is the number of pairs of people who are taller than everyone between them.

Examples2

  1. Example 1

    Input
    3
    2
    1
    3
    
    Expected output
    3
    
  2. Example 2

    Input
    6
    1
    3
    2
    6
    4
    5
    
    Expected output
    7