- Related Questions & Answers
- Consecutive elements sum array in JavaScript
- Return the sum of two consecutive elements from the original array in JavaScript
- Thrice sum of elements of array - JavaScript
- Absolute sum of array elements - JavaScript
- Sum of consecutive numbers in JavaScript
- Maximum sum of increasing order elements from n arrays in C++
- Maximum consecutive 1s after n swaps in JavaScript
- Sum of distinct elements of an array - JavaScript
- Sum of two elements just less than n in JavaScript\n
- Sum of distinct elements of an array in JavaScript
- Find elements of array using XOR of consecutive elements in C++
- Maximum sum of increasing order elements from n arrays in C++ program
- Finding sum of alternative elements of the array in JavaScript
- Parts of array with n different elements in JavaScript
- Maximum sum of difference of adjacent elements in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

10 12

Advertisements