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

127
Vistas
A sum of consecutive numbers in array

one more time i need help of community. There is this code. I underrstand pretty everything but not the ending. I am counting on you. So we have a function where we add an indicated elements to each other

  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 Respuestas
Responde la pregunta

0

I'm not convinced there aren't bugs in that code. The inner loop needs to only be executed once. temp_sum needs to be incremented with nums[i] and decremented with nums[i-k+1] before evaluating if (temp_sum > result).

This line:

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

Is apparently decrementing the running summation by excluding the last element of the previously evaluated subset. But it needs to be doing this before the if (temp_sum > result) statement.

I rewrote the implementation to something that I think is cleaner, faster, and more correct.

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 Denunciar

0

Here is another short solution (not a one-liner!) that should also do the job. I now understand what the parameter k was supposed to do and worked it into my solution too.

I now reverse the array in order to avoid having to do any housekeeping on intermediate lists (for those cases where more than k consecutive numbers were encountered).

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 && i-j<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))

The Array.prototype.reduce() function call accumulates the sums of consecutive number sequences into an array which is then spread out as arguments for the outer Math.max()-call to find and return the highest of the collected sums.

Update ( hopefully the last one :D )
Following @BenStephen's helpful comment, here is a short script that will calculate the largest sum of k consecutive numbers in an array (the numbers do not need to form a "sequence" of any kind).

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