還有一次我需要社區的幫助。有這個代碼。我明白一切,但不明白結局。我指望你。所以我們有一個函式,我們將一個指定的元素相互添加
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))
uj5u.com熱心網友回復:
我不相信該代碼中沒有錯誤。內回圈只需要執行一次。在評估 if 之前,temp_sum 需要用 nums[i] 遞增并用 nums[i-k 1] 遞減(temp_sum > result)。
這一行:
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;
}
uj5u.com熱心網友回復:
這是另一個也可以完成作業的簡短解決方案(不是單行!)。我現在了解引數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()-call找到并回傳最高收集的總和。
更新(希望是最后一個: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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/359207.html
標籤:javascript 数组 for循环
下一篇:通過https://localhost:8000/訪問時,Localhost拒絕在WSL2上連接,但在使用內部WSLIP地址時有效
