I am working on code where I need to find the count of array group with difference between the elements of the array group should be less than k
Example
The numbers of awards per movie are awards = [1, 5, 4, 6, 8, 9, 2],
and the maximum allowed difference is k = 3.
-
One way to divide the movies into the minimum number of groups is:
The first group can contain [2, 1]. The maximum difference between
awards of any two movies is 1 which does not exceed k. -
The second group can contain [5, 4, 6]. The maximum difference between awards of
any two movies is 2 which does not exceed k -
The third group can
contain [8, 9]. The maximum difference between awards of any two
movies is 1 which does not exceed k. The movies can be divided into
a minimum of 3 groups.
below is my code
But it is not working. What I am doinng wrong. Please help me.
function minimumGroups(nums, k) {
// Write your code here
nums.sort((a,b) => (a - b))
let result = 0
for(let i = 0; i < nums.length; i++){
if(i > 0 && nums[i] === nums[i - 1])
continue
for(let j = i + 1; j < nums.length; j++){
let diff = nums[j] - nums[i]
if(diff === k){
result += 1
break
}
if(diff > k) break
}
}
return result
}