How to sum first n number of entries in an array?

Viewed 2693

I'm new to programming and learning about javascript recursion. It's my 5th day with JavaScript and following an online course. The problem is that I need to sum up first n numbers of entries (first 3 numbers in this case) in an array. But I'm ending up with sum of all and that also I'm not sure about.

var theArray = [1, 3, 8, 5, 7];

function sum(arr, n) {
  if (n <= 0) {
    return 1;
  } else {
    return arr[n - 1] + sum(arr, n - 2);
    //assuming n is arr.length and n-1 is hence arr.length-1
  }
}

console.log(sum(theArray, 3));

What am I doing wrong? I checked most people are solving such with reduce method or with for of loop. I didn't learn those yet in the curriculum. But I know 'for loop' but that's good if the numbers are in incremental order I guess. Please explain this problem in my level.

2 Answers

When implementing something recursively, it's a good idea to think about the base condition. It does look like that's where you started, but your logic is flawed. n is the number of elements you would like to sum together. So let's say you want to sum the first n=3 elements of the array [2,3,4,5,6] and get 9. Here are the iterations.

  1. return arr[n-1] + sum(arr, n-1) // arr[2] + sum(arr, 2) === 4 + sum(arr, 2) === 4 + 5
  2. return arr[n-1] + sum(arr, n-1) // arr[1] + sum(arr, 1) === 3 + sum(arr, 2) === 3 + 2
  3. return arr[n-1] // arr[0] === 2 (base case when n is 1)

I didn't solve the problem for you since this is obviously a school exercise, but the point is that the base case and the recursive call that you have are both slightly off.

Array of undetermined length, find the largest sum possible for any 3 consecutive numbers.

  1. [2,0,1,100,200,10,7,2, 300,2,1 0] here 100,200,10 = 310 is the correct answer. Here only the combination of these 3 numbers produces the largest sum.

  2. [2,1,0,20,71 = 0+20+7 = 27 is the answer that you should return.

const findMax = (numberArray) => {
let first = 0;
let second = 1;
let third = 2;
let max = 0;

    for(; third < numberArray.length; first++, second++, third++) {
    if(max < (numberArray[first] + numberArray[second] + numberArray[third])) {
        max = numberArray[first] + numberArray[second] + numberArray[third];
    }
    }
  return max;
}

console.log('Max sum of three consecutive numbers in array ===>  ',findMax([2, 0, 100, 200, 10, 7, 2, 300, 2, 10]));

Related