Search code examples
javascriptarrayssumnumbersclosures

How accelerate reduce and forEach method?


I wrote a program to count sum of range of array items, but still can not pass the quiz because my code is slow: Execution Timed Out (12000 ms). How can I speed up my code to 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]])


Solution

  • Here's a faster and simpler solution. Iterates over range just once and collects all the sum totals, then maps it into sum ranges, then returns the max:

    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]]);