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]])
arr.slicecreates a copy of the array so maybe you don't want to do that.