1

Added maximum number according to the input length should be returned.

For example, if the length is 2 then the max among arr[0] + arr[1], arr[1] + arr[2], arr[2] + arr[3] should be returned.

Input is array and length.

I solved this in a real job interview but I think there will be a way not to use nested loop.

const add = (arr, len) => {
  let rtnVal = 0

  for (let i = len - 1; i < arr.length; i++) {
    let temp_idx = i;
    let temp_sum = 0;
    for (let j = 0; j < len; j++) {
      temp_sum = (temp_sum || 0) + arr[temp_idx]
      temp_idx -= 1
    }

    if (temp_sum > rtnVal) {
      rtnVal = temp_sum
    }
  }

  return rtnVal
}

console.log(add([1, 2, 3, 4, 5, 6, 7, 8, 9], 4))

I expect the output 30

// enhanced nested loop

const add = (arr, len) => {
  let rtnVal = 0;
  for(let i=len-1;i<arr.length;i++){
    let sum = 0
    for(let j=i;j>=i-len+1;j--){
      sum += arr[j]
    }
    if (sum > rtnVal) rtnVal = sum
  }
  return rtnVal

}
console.log(add([9, 9, 9, 4, 5, 6, 7, 8, 9], 3))

2

2 Answers 2

4

Use a moving window. Add up len numbers starting at the beginning. Then continue through the array adding the next number and subtracting the trailing number.

const add = (arr, len) => {
  return arr.reduce((a,v,i,arr) => {
    a.running += v;
    if(i >= len) {
      a.running -= arr[i-len];
    }
    if(i+1 >= len && a.largest < a.running) {
      a.largest = a.running;
    }
    return a;
  }, {
    largest: Number.NEGATIVE_INFINITY,
    running: 0
  }).largest;
}

console.log(add([1,2,3,4,5,6,7,8,9],4)); // 30
console.log(add([-1,-1,-1,-1],2)); // -2
console.log(add([1],1)); // 1
Sign up to request clarification or add additional context in comments.

4 Comments

The condition a.largest < a.running should only be executed when i >= len-1, otherwise the result would be (wrong) -1 for len > 1 and arr full of -1.
@user202729 I'm not sure that i >= len-1 is correct but I do see that the constraint needs to, at least, be i >= len to account for negative integers near the beginning of the array. I'm going to assume that arr.length >= len is true.
No, this is still wrong because it doesn't take into account the leftmost array. Try a = [1], len = 1.
@user202729 Ah, okay, I see now.
1

Assuming its sorted like your example. You can use negative slice to select from end and then reduce the array.

const add = (arr, len) => arr.slice(len > arr.len ? arr.len : -len).reduce((total, num) => total + num)

console.log(add([1, 2, 3, 4, 5, 6, 7, 8, 9], 4))

1 Comment

I'm sorry but your answer doesn't bring the answer I expect. I think this only works when input array values are sorted. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.