[Solved] Function with maximum possible sum of some of its k consecutive numbers [closed]


There are several ways to do this, you can do this with the help of traditional for, Math.max(), indexOf() and Array#reduce.

First of all, you need to find the maximum value of your input array, then you should pop it and according to the iteration count, iterate to find the next maximum value. Then after you find all the maximum values you need to sum them up at last.

function maxOfSumChain(arr, length) {
  const maxArr = [];
  for (let i = 0; i < length; i++) {
    const max = Math.max(...arr);
    maxArr.push(max);
    arr.splice(arr.indexOf(max), 1);
  }

  return maxArr.reduce((a, b) => a + b, 0);
}

console.log(maxOfSumChain([1, 3, 2, 6, 2], 3));
console.log(maxOfSumChain([1, 3, 2], 2));

0

solved Function with maximum possible sum of some of its k consecutive numbers [closed]