I have the following code:
float difference = 6.5;
float values[] = {1.3, 7.0, 6.4, 15.1};
float min;
float max;
I want to assign min and max so that their difference max-min is closest to difference.
In this case, min should be 1.3 and max 7.0.
How can I do that ?
O(n) solution, assuming the array is sorted and n is the focal difference:
Start off with two iterators at both ends of the array:
iandj.1) Check differences
j-i,(j-1)-i,j-(i+1).2) If the minimum is
j-i, you found the answer.3) If
(j-1)-iis closest, move iteratorjtoj-1go to 1).4) If
j-(i+1)is closest, move iteratoritoi+1go to 1).A run on your example:
Move iterator j one position left:
Return current results, since
j-i = 5.7is closest.