/** * Write a function which accepts an array of integers * and a number called n. * * The function should calculate the maximum sum of n consecutive * elements in the array. */ const maxSubArraySum = (arr, n) => { if (!arr.length) return null; let maxSum = 0; let tempSum = 0; // Loop n times and add those n values together // and store value as maxSum for (let i = 0; i < n; i++) { maxSum += arr[i]; } // Temp sum will be used for comparison later tempSum = maxSum; for (let i = n; i < arr.length; i++) { // Set temp sum to remove the oldest of the n nums // and tack on the next num in the array // i.e. slide the window over one tempSum = tempSum - arr[i - n] + arr[i]; // Return the largest value maxSum = Math.max(maxSum, tempSum); } return maxSum; }; console.log(maxSubArraySum([1, 2, 5, 2, 8, 1, 4], 2)); // 10 console.log(maxSubArraySum([1, 2, 5, 2, 8, 1, 4], 4)); // 17 console.log(maxSubArraySum([4, 2, 1, 6], 1)); // 6 console.log(maxSubArraySum([4, 2, 1, 6], 4)); // 13 console.log(maxSubArraySum([], 4)); // null