【问题标题】:A sum of consecutive numbers in array数组中连续数字的总和
【发布时间】:2021-12-25 08:48:57
【问题描述】:

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

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

【问题讨论】:

  • 你有什么问题?
  • 很抱歉造成混乱。
  • temp_sum -= nums[i - k + 1];这条线。你能详细给我解释一下吗?我们要删除什么以及为什么在此操作中使用“1”
  • 因为你想要最大 k 个连续总和,所以你必须在添加 k 个元素后删除前一个元素。此方案效率不高,您可以用更少的代码更轻松高效地解决此问题。
  • 您似乎嵌套了 for 循环与相同的循环变量 i。如果没有问题,这至少是不寻常的,因为您将在使用内部循环时更改外部循环的 i

标签: javascript arrays for-loop


【解决方案1】:

我不相信该代码中没有错误。内循环只需要执行一次。 temp_sum 需要以 nums[i] 递增并以 nums[i-k+1] 递减,然后再评估是否为 (temp_sum &gt; result)

这一行:

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

显然是通过排除先前评估的子集的最后一个元素来减少运行总和。但它需要在if (temp_sum &gt; 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;
}

【讨论】:

  • 感谢您的宝贵时间和建议。你是伟大的社区:) 我会分析你发送的所有内容。美好的一天:)
【解决方案2】:

这是另一个简短的解决方案(不是单行!)也应该可以完成这项工作。我现在明白了参数k 应该做什么,并将它也应用到我的解决方案中。

我现在反转数组以避免必须对中间列表进行任何内务处理(对于遇到超过k 连续数字的情况)。

const arr = [1, 2, 3, 4, 6, 7, 8, 9, 4, 5, 6, 10, 1];

function maxListSum(arr,k){
 let j=0;
 return Math.max(...arr.reverse().reduce((l, c, i, a) => {
    if (i && c == a[i - 1] - 1 && i-j<k){ // 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);j=i;}     // otherwise: start a new sum in l
    return l
  }, []))
}

console.log(maxListSum(arr,3))

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

更新(希望是最后一个:D)
在@BenStephen 的有用评论之后,这是一个简短的脚本,它将计算数组中 k 个连续数字的最大总和(这些数字需要形成任何类型的“序列”)。

function largestSumOfKNums(arr,k){
 for (var s,i=0,sum=0;i<=arr.length-k;i++){
  s = arr.slice(i,i+k).reduce((a,c)=>a+c);
  if (s>sum) sum=s;
 }
 return sum
}

console.log(largestSumOfKNums([20,30,-100,4,3],2))

【讨论】:

  • 为什么称其为“单线”?它有一个带有两个if 语句和一个return 语句的语句块...
  • 是的——没错——我忽略了这一点。所以:它不是单行! :-)
  • 您没有考虑k 参数。还是你?
  • @selbie:现在和我一起“掉一分钱”! :D 不,我还没有在我的答案中使用k 参数,是的,我现在看看如何包含它! ;-)
  • 好的,参数k(求和的最大连续元素数)也已经包含在我的解决方案中了。
猜你喜欢
  • 1970-01-01
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
  • 1970-01-01
  • 2015-11-01
  • 1970-01-01
  • 2019-09-26
相关资源
最近更新 更多