[英]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.