Given an array $A$ of length $N<10^6,$ how many subarrays have $\text{max}(A[x:y]) - \text{min}(A[x:y]) {\le} K$?

41 Views Asked by At

Given any K and an array of length $N$ what is the most efficient way to find the number of unique subarrays that satisfy this constraint? I believe there is an $O(N)$ solution using monotonic queues but am unsure of the specifics. Unique refers to the range of the original array that the subarray covers.