I have an array which stores a set of positive x coordinates in sorted way,
say arr={1, 4, 5, 9, 12, 45}
etc.
And I have a maximum distance k
which I can go from one point to another point let k=3
.
Now, given two points x
and y(arr[x]<arr[y])
I need to determine if I can reach from x
to y
. I will be able to reach y
from x
if distance between every two hop is less that or equal to k
.
Here suppose x=1 y=4
then I can go from 1->2 then 2->3 but since distance between 3 and 4 is greater than 3 I can't go so in this case I can't reach.
But if x=1
and y=2
then I can reach.
It can be simply solved with O(n). I have created a for loop from arr[x]
to arr[y]
and for each pair of points I check if distance between them is less than or equal to k
.
But I want better algorithm. I am thinking of doing something like binary search. Can anybody please suggest a good algorithm?