Problem 697
Count Subarrays With Fixed Bounds
Hard · 30 pts · Array, Sliding Window, Monotonic Queue
Problem
Count the blocks of consecutive elements whose minimum equals exactly MINK and whose maximum equals exactly MAXK. Blocks at different positions count separately. Scan once, remembering the last index where MINK appeared, the last index where MAXK appeared, and the last index holding a value outside [MINK, MAXK]. A block ending at i is valid for every start after the last bad index and at or before both last-seen indices, which adds max(0, min(lastMin, lastMax) - lastBad).
Input
The first line contains N, MINK and MAXK. The second line contains N integers.
Output
Print the number of fixed-bound subarrays.
Constraints
2 <= N <= 100000; 1 <= A[i], MINK, MAXK <= 10^6
Example input
6 1 5 1 3 5 2 7 5
Example output
2
Explanation
In 1 3 5 2 7 5 with MINK = 1 and MAXK = 5, the blocks 1 3 5 and 1 3 5 2 have minimum 1 and maximum 5. Any longer block includes 7, so the answer is 2.