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 :
Number of valid segments to the right of :
Thus, the total number of segments whose maximum is strictly smaller than the maximum of the permutation is:
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)