如何加速 reduce 和 forEach 方法?

How accelerate reduce and forEach method?

我写了一个程序来计算数组项范围的总和,但由于我的代码很慢,仍然无法通过测验:Execution Timed Out (12000 ms)。如何将我的代码加速到 pass the quiz?

function maxSum(arr, range) {
  let result = -Infinity
  range.forEach(el => {
    let sumArr = arr.slice(el[0],el[1]+1).reduce((a,b) => a+b)
    sumArr > result && (result = sumArr)
  })
  console.log(result)
return result 
}
maxSum([1,-2,3,4,-5,-4,3,2,1],[[0,8],[1,3],[0,4],[6,8]])

这是一个更快更简单的解决方案。迭代 range 一次并收集所有总和,然后将其映射到总和范围,然后 returns 最大值:

function maxSum(arr, range) {
  let left = [0];
  let total = 0;
  
  for (let num of arr) {
    left.push(total += num);
  }

  let sums = range.map(([a, b]) => left[b + 1] - left[a]);
  
  let result = Math.max(...sums);
  console.log(result);
  return result;
}

maxSum([1, -2, 3, 4, -5, -4, 3, 2, 1], [[0, 8], [1, 3], [0, 4], [6, 8]]);