Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Una suma de números consecutivos en una matriz

una vez más necesito ayuda de la comunidad. Hay este código. Entiendo bastante todo menos el final. Estoy contando contigo. Entonces tenemos una función donde agregamos los elementos indicados entre sí

 function array_max_consecutive_sum(nums, k) { let result = 0; let temp_sum = 0; // veriable where we collects results for (var i = 0; i < k - 1; i++) { // first loop where we go through elements but it is limited to value of k // result temp_sum += nums[i]; for (var i = k - 1; i < nums.length; i++) { // the second loop but this time we start from position where we had finished temp_sum += nums[i]; } // condiition statement which overwrites if (temp_sum > result) { result = temp_sum; } // How should i analyze this line of code. Could you simplify it for me? We have a veriable, from which we will remove, what to be specific? Another question is why we have to use "1" in this operation? temp_sum -= nums[i - k + 1]; } return result; } console.log(array_max_consecutive_sum([1, 2, 3, 14, 5], 3))
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

No estoy convencido de que no haya errores en ese código. El bucle interno solo debe ejecutarse una vez. temp_sum debe incrementarse con nums[i] y disminuirse con nums[i-k+1] antes de evaluar if (temp_sum > result) .

Esta línea:

 temp_sum -= nums[i - k + 1];

Aparentemente está disminuyendo la suma en ejecución al excluir el último elemento del subconjunto evaluado previamente. Pero debe estar haciendo esto antes de la declaración if (temp_sum > result) .

Reescribí la implementación a algo que creo que es más limpio, más rápido y más correcto.

 function array_max_consecutive_sum(nums, k) { if ((nums.length < k) || (k <= 0)) { return 0; } let result = 0; let temp_sum = 0; // iterations is the number of sub arrays of length k to evalaute let iterations = nums.length - k + 1; // do first iteration where we sum up nums[0] up to and including nums[k-1] for (let i = 0; i < k; i++) { temp_sum += nums[i]; } result = temp_sum; let start = 0; iterations--; // we just completed the first iteration // now evaluate each subset by subtracting the first item // from the left and adding in a new item onto the right for (let i = 0; i < iterations; i++) { temp_sum -= nums[start]; // remove the first element of the previous set temp_sum += nums[start+k]; // add the last element of the new set start++; // evaluate this subset sum if (temp_sum > result) { result = temp_sum; } } return result; }
about 4 years ago · Juan Pablo Isaza Relatório

0

Aquí hay otra solución corta (¡ no de una sola línea!) que también debería hacer el trabajo. Ahora entiendo lo que se suponía que debía hacer el parámetro k y también lo incorporé a mi solución.

Ahora invierto la matriz para evitar tener que hacer limpieza en las listas intermedias (para aquellos casos en los que se encontraron más de k números consecutivos).

 const arr = [1, 2, 3, 4, 6, 7, 8, 9, 4, 5, 6, 10, 1]; function maxListSum(arr,k){ let j=0; return Math.max(...arr.reverse().reduce((l, c, i, a) => { if (i && c == a[i - 1] - 1 && ij<k){ // as of second element: if it is a consecutive number: l[l.length - 1] += c // add to current sum in l[l.length-1] } else {l.push(c);j=i;} // otherwise: start a new sum in l return l }, [])) } console.log(maxListSum(arr,3))

La llamada a la función Array.prototype.reduce() acumula las sumas de secuencias numéricas consecutivas en una matriz que luego se distribuye como argumentos para la Math.max() externa para encontrar y devolver la mayor de las sumas recopiladas.

Actualización (esperemos que la última: D)
Siguiendo el útil comentario de @BenStephen, aquí hay una breve secuencia de comandos que calculará la suma más grande de k números consecutivos en una matriz (los números no necesitan formar una "secuencia" de ningún tipo).

 function largestSumOfKNums(arr,k){ for (var s,i=0,sum=0;i<=arr.length-k;i++){ s = arr.slice(i,i+k).reduce((a,c)=>a+c); if (s>sum) sum=s; } return sum } console.log(largestSumOfKNums([20,30,-100,4,3],2))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda