尝试使用 Kadane 的算法,如下所述:https ://www.youtube.com/watch?v=OexQs_cYgAQ&t=721s
在这个数字数组上:[-5, 10, 2, -3, 5, 8, -20]
。
答案是10 + 2 – 3 + 5 + 8 = 22
但是,当我运行以下代码时,我得到了这个:
sumArray = [ 0, 20, 24, 24, 28, 44, 44 ]
不知道如何24
和更高的数字进入那里:(并且22
丢失了。
下面的代码:
const myArray = [-5, 10, 2, -3, 5, 8, -20];
const findMaxConsecutiveSum = (arr) => {
const sumArray = [];
let max_so_far = 0;
let max_ending_here = 0;
for (let i = 0; i < arr.length; i++) {
max_ending_here = max_ending_here + arr[i];
// console.log('position:', i, arr[i]);
// console.log(max_ending_here = max_ending_here + arr[i]);
// console.log('max_ending_here', max_ending_here);
if (max_ending_here < 0) {
max_ending_here = 0;
}
else if (max_so_far < max_ending_here) {
max_so_far = max_ending_here;
}
// console.log('max_so_far', max_so_far);
sumArray.push(max_so_far);
}
return sumArray;
}
console.log(findMaxConsecutiveSum(myArray));
这个想法是我只需填写 sumArray 然后按最大数对其进行过滤。但是我没有得到22
,而是一大堆更大的数字?
任何想法为什么?