Faster Algorithm for JavaScript function call within a function

前端 未结 3 1134
野的像风
野的像风 2021-01-17 06:19

I have written a function and called another function inside but my tests show that it is not time optimized. How can I make the following code faster?

    f         


        
3条回答
  •  鱼传尺愫
    2021-01-17 07:16

    Full working code based on @MBo's excellent optimization. This passes all the tests at https://www.codewars.com/kata/the-maximum-sum-value-of-ranges-challenge-version/train/javascript, which I gather is where this problem comes from.

    function maxSum(arr, ranges) {
      var max = null;
    
      var sums = [];
      var sofar = 0;
      for (var i = 0; i <= arr.length; i++) {
        sums[i] = sofar;
        sofar += arr[i];
      }
    
      for (var i = 0; i < ranges.length; i++) {
        var sum = sums[ranges[i][1]+1] - sums[ranges[i][0]];
        if (max === null || sum > max) {
          max = sum;
        }
      }
    
      return max;
    }
    

提交回复
热议问题