Can we do like that ( tell me if I m wrong ) , after sorting for each element by applying Binary search we will find the element X such that abs(X-current element) <=K ,Like this-
Bro we have to count all subarrays whose first and last element difference is less than or equal to K that means simple count all pairs whose abs difference is less than K
Sorting is predetermining the complexity bound of O(N log(n)).
Suppose if a desired sub-array ends at i. Then we only have to look for no. of times a[i]+k and a[i]-k occurs before i. If the numbers are in range we can create a frequency array, else we can use a HashMap. Either way complexity will be O(n).
EDIT 1: I didn’t read the part less than equal to. Sorry MY bad