Max sub array sum algorithm in JavaScript

Given an array of numbers and an integer “width”, find the max sum of a contiguous sub-array with that width in positions.

function maxSubArraySum(numbers, width) {
  if (width >= numbers.length) {
    return numbers.reduce((sum, num) => sum + num, 0)
  }
  let subArraySum = numbers.slice(0, width).reduce((sum, num) => sum + num, 0);
  let maxSubArraySum = subArraySum;
  for (let t = 0, h = width; h < numbers.length; t++, h++) {
    subArraySum -= numbers[t];
    subArraySum += numbers[h];
    maxSubArraySum = Math.max(maxSubArraySum, subArraySum);
  }
  return subArraySum;
}

This algorithm has $O(n)$ time complexity and $O(1)$ space complexity.


View post: Max sub array sum algorithm in JavaScript