【发布时间】: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