
It is guaranteed that there exists at least one pair of points in the given array/list that satisfies the constraint |'xi - xj'| <= 'K'.
The first line contains a single integer ‘T’ denoting the number of test cases. The test cases are as follows.
The first line of each test case contains two integers separated by single space ‘N’ and ‘K’, where ‘N’ denotes the number of points in the array/list and the number ‘K’ described in the constraint of the above equation.
The next ‘N’ line contains two integers separated by space which denotes the coordinates of the points in the given array/list.
For each test case, print a single line that contains an integer denoting the maximum value of the given equation.
You don’t need to print anything, it has already been taken care of. Just implement the given function.
1 <= 'T' <= 50
2 <= 'N' <= 10^4
-10^4 <= 'xi, yi' <= 10^4
0 <= 'K' <= 10^4
Where (xi, yi) denotes the coordinates of i-th point of the given array/list.
Time Limit: 1 sec
The basic idea of this approach is to consider all the possible pairs of points in the given array/list and check for the maximum value of the equation.
The basic idea of this approach is to use a sliding window technique to solve this task.
Let’s define a window as a subarray (i, j) of the given array/list where i and j denote the left and right end of the window such that |xi - xj| <= K.
Now we are looking for a pair of points that maximizes the value of the function yi + yj + |xi - xj|. Observe that, for j > i, we can rewrite this function as yi + yj +xj - xi because the array/list is sorted by x-values in non-decreasing order (It has been given in the problem description).
Now note that the value (xj + yj) is fixed if we are at jth index. So the task breaks down into finding the maximum value of (yi - xi) such that i < j. We can easily solve this problem using the max-heap to store such values so that we can efficiently get the maximum value.
STEPS :
We need to find the maximum value of (yj + yi + | xi - xj |) . Since it is given in the problem description that the points array/list are sorted in non-decreasing order by x-values which means we can write the equation as yi - xi + (xj + yj) for i < j.
Now note that the value (xj + yj) is fixed if we are at the jth index. So the task breaks down into finding the maximum value of yi - xi such that i < j. We can easily solve this problem using a deque. This problem is a slight modification of the Sliding Window Maximum problem.
The idea here is to use the sliding window technique and to maintain a non-increasing deque for the window such that the front element denotes the index of point for which (yi - xi) is maximum.