find minimum group of array with difference less than k code example

find minimum group of array with difference less than k

3

3 Examples

0
// CPP code to find count of Pairs with
// difference less than K.
#include <bits/stdc++.h>
using namespace std;
 
int countPairs(int a[], int n, int k)
{
    int res = 0;
    for (int i = 0; i < n; i++)
      for (int j=i+1; j<n; j++)
         if (abs(a[j] - a[i]) < k)
            res++;
 
    return res;
}
 
// Driver code
int main()
{
    int a[] =  {1, 10, 4, 2};
    int k = 3;
    int n = sizeof(a) / sizeof(a[0]);
    cout << countPairs(a, n, k) << endl;
    return 0;
}

0
function minimumGroups(arr, k) {
    // Write your code here
  arr.sort((a, b) => a-b);  // this line is updated.
  let start = 0;
  if(arr.length == 0) return 0;
  // If arr has some value then at least can form 1 group
  let count = 1;
  for(let i = 0; i < arr.length; i++) {
    if(arr[i] - arr[start] > k) {
      count++;
      start = i;
    }
  }
  return count;
};

console.log(minimumGroups([ 1, 13, 6, 8, 9, 3, 5 ], 4));
by on

0
#include <stdio.h>
#include <math.h>
// function for finding maximum group difference of array
int maxKDiff (int arr[], int n, int k){
   // sum of array
   int arrsum = 0;
   int i;
   for(i=0;i<n;i++)
      arrsum+=arr[i];
   //sum of smallest k
   int sumk=0;
   for(i=0;i<k;i++)
      sumk+=arr[i];
   // difference for k-smallest
   int D1 = abs(arrsum - 2*sumk);
   //sum of largest k elements
   sumk=0;
   int j=0;
   for(i=n-1;j<4;i--){
      sumk+=arr[i]; j++;
   }
   // difference for k-largest
   int D2 = abs(arrsum - 2*sumk);
   int maxD=D1>=D2?D1:D2;
   // return maximum difference value
   return maxD;
}
// driver program
int main(){
   int arr[] ={ 2,3,2,10,7,12,8};
   int n = 7;
   int k = 3;
   sort(arr,n); // to sort array in ascending order
   printf("Maximum difference between the group of k-elements and rest of the array : %d" , maxKDiff(arr,n,k));
   return 0;
}

Other Code Examples