So basically I have an array of n
integers (positive only). I want to have k
number of integers from this array into a separate array (k<n)
such that the difference between these k numbers is the minimum amongst every other k
pairs of integers in an array.
If k is 1, I just need to return the max integer of the array.
I want to implement this in JavaScript. I understand how to run this problem for the values k=1
and k=2
. But I don't grasp the general concept of this problem.
For eg:
Array = [6,22,21,63,99,77]
I sorted this array in ascending order. After this I don't understand how to proceed further.
After sorting the array it becomes similar to a sliding window problem.
Run a loop from i=0
to nk
and check the following.
Find the minimum difference between arr[i+k]
and arr[i]
. The index at which this occurs is your subset of k
integers you want. You can check this link for more details and coding help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.