Kaosar and Segments#12325

Kaosar and Segments (Editorial)

Problem Author:

AlKaosar Hussain

Prepared by:

AlKaosar Hussain

Edited by:

Hasan Saleh (MathModel)

Solution

We are given a permutation of . Clearly, the maximum element of the permutation is .

Let the position of in the permutation be (1-based indexing). Any contiguous subarray (segment) that does not include will have a maximum strictly less than . Therefore, only the segments fully contained in [1, i-1] (to the left of ) and [i+1, n] (to the right of ) contribute to the answer.

Recall that the number of non-empty subarrays of length is \frac{k(k+1)}{2}.

  • Number of valid segments to the left of :

    \frac{i(i-1)}{2}
  • Number of valid segments to the right of :

    \frac{(n-i)(n-i+1)}{2}

Thus, the total number of segments whose maximum is strictly smaller than the maximum of the permutation is:

\frac{i(i-1)}{2} + \frac{(n-i)(n-i+1)}{2}

Complexity .

for _ in range(int(input())):
    n=int(input())
    p=list(map(int, input().split()))
    m=p.index(n)
    ans=0
    ans+=(m*(m+1))//2
    ans+=((n-m)*(n-m-1))//2
    print(ans)