0

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

7
  • Your snippets takes some milliseconds. So... If you want help with the "12000 ms" code than post it... Commented Jun 23, 2020 at 14:31
  • 2
    arr.slice creates a copy of the array so maybe you don't want to do that. Commented Jun 23, 2020 at 14:31
  • I think one method to speed it up may be to remove subsets from the equation. For example, all [1,3], [0,4] and [6,8] are in [0,8]. Therefore sum [0,8] is maximum and you only need to calculate it. Commented Jun 23, 2020 at 14:33
  • Felix Kling Looking strange ... Commented Jun 23, 2020 at 14:33
  • 1
    Ambu , there is a negative numbers ... Commented Jun 23, 2020 at 14:34

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

map(([a, b]) => left[b + 1] - left[a]) - interesting use case
pretzelhammer , please , can you show detailed description of this function ?
precalculate sum(0...n) for n=[0...length], return sum(0...n1) - sum(0..n2) = sum(n1..n2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.