Maximum sum of n consecutive elements of array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers, say arr, as the first argument and a number, say num, as the second argument.

The second argument will always be smaller than or just equal to the length of the array. Our function should find and return the num number of consecutive elements from the array that sums the greatest.

For example −

If the inputs are −

const arr = [2,5,3,4,6];
const num = 2

The output for the above input should look like this −

const output = 10

because 6 and 4 are those two consecutive elements that sum the greatest.

We can solve this problem with the sliding window technique in a linear time and constant space solution.


Following is the code −

const arr = [2, 5, 3, 4, 6];
// helper function to find sum of an array
const findSum = arr => arr.reduce((acc, val) => acc + val);
const maximumSum = (arr = [], num = 1) => {
   let left = 0, right = left + num;
   let sum = findSum(arr.slice(left, right));
   for(; right <= arr.length; right++, left++){
      sum = Math.max(findSum(arr.slice(left, right)), sum);
   return sum;
console.log(maximumSum(arr, 2));
console.log(maximumSum(arr, 3));


Following is the output on console −

Published on 10-Dec-2020 12:23:10