繁体   English   中英

数组中连续数字的总和

[英]A sum of consecutive numbers in array

还有一次我需要社区的帮助。 有这个代码。 我明白一切,但不明白结局。 我指望你。 所以我们有一个函数,我们将一个指定的元素相互添加

  function array_max_consecutive_sum(nums, k) {
    let result = 0;
    let temp_sum = 0;
    // veriable where we collects results
    for (var i = 0; i < k - 1; i++) {
        // first loop where we go through elements but it is limited to value of k
        // result
        temp_sum += nums[i];
        for (var i = k - 1; i < nums.length; i++) {
            // the second loop but this time we start from position where we had finished
            temp_sum += nums[i];
        }
        // condiition statement which overwrites
        if (temp_sum > result) {
            result = temp_sum;
        }
        // How should i analyze this line of code. Could you simplify it for me? We have a veriable, from which we will remove, what to be specific? Another question is why we have to use "1" in this operation? 
        temp_sum -= nums[i - k + 1];
    }
    return result;
  }
        
  console.log(array_max_consecutive_sum([1, 2, 3, 14, 5], 3))

我不相信该代码中没有错误。 内循环只需要执行一次。 在评估 if (temp_sum > result)之前,temp_sum 需要用 nums[i] 递增并用 nums[i-k+1] 递减。

这一行:

temp_sum -= nums[i - k + 1];

通过排除先前评估的子集的最后一个元素,显然减少了运行总和。 但它需要在if (temp_sum > result)语句之前执行此操作。

我将实现重写为我认为更干净、更快、更正确的东西。

function array_max_consecutive_sum(nums, k) {

    if ((nums.length < k) || (k <= 0)) {
        return 0;
    }
    
    let result = 0;
    let temp_sum = 0;

    // iterations is the number of sub arrays of length k to evalaute
    let iterations = nums.length - k + 1;

    // do first iteration where we sum up nums[0] up to and including nums[k-1]
    for (let i = 0; i < k; i++) {
        temp_sum += nums[i];
    }
    result = temp_sum;

    let start = 0;
    iterations--; // we just completed the first iteration

    // now evaluate each subset by subtracting the first item
    // from the left and adding in a new item onto the right
    for (let i = 0; i < iterations; i++) {

        temp_sum -= nums[start];    // remove the first element of the previous set
        temp_sum += nums[start+k];  // add the last element of the new set
        start++;

        // evaluate this subset sum
        if (temp_sum > result) {
            result = temp_sum;
        }
    }

    return result;
}

这是另一个也可以完成工作的简短解决方案(不是单行!)。 我仍然不明白参数k的作用,所以我的解决方案没有它也能工作。

 const arr = [1, 2, 3, 4, 7, 8, 9, 4, 5, 6, 10, 1], maxListSum = Math.max(...arr.reduce((l, c, i, a) => { if (i && c == a[i - 1] + 1) // as of second element: if it is a consecutive number: l[l.length - 1] += c // add to current sum in l[l.length-1] else l.push(c) // otherwise: start a new sum in l return l }, [])) console.log(maxListSum)

Array.prototype.reduce()函数调用将连续数字序列的总和累积到一个数组中,然后将其作为外部Math.max()调用的参数展开,以查找并返回收集到的总和中的最高值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM