Skip to content

Instantly share code, notes, and snippets.

@torressam333
Created December 15, 2022 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torressam333/a58df0a16906e2c362d61839f9f788b3 to your computer and use it in GitHub Desktop.
Save torressam333/a58df0a16906e2c362d61839f9f788b3 to your computer and use it in GitHub Desktop.
Solves the max sub array sum with O(n) time complexity using JavaScript.
/**
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment