Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
Find minimum group of array with difference less than k

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(arr, k) {
    // Write your code here
arr.sort();
  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;
}

Some of hidden test cases are not passing for same scenario

Arr =[ 1, 13, 6, 8, 9, 3, 5 ] and K= 4 Expected output is 3 but I am getting 2

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This code snippet fixes the code by update the .sort().

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));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda