0

尝试使用 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,而是一大堆更大的数字?

任何想法为什么?

4

2 回答 2

2

你使实现比它需要的复杂得多。从关于Kadane 算法的帖子中,代码应如下所示:

def max_subarray(A):
    max_ending_here = max_so_far = A[0]
    for x in A[1:]:
        max_ending_here = max(x, max_ending_here + x)
        max_so_far = max(max_so_far, max_ending_here)
    return max_so_far

那里所述的算法希望返回单个数字,而不是数组。翻译成 JS,看起来像:

const myArray = [-5, 10, 2, -3, 5, 8, -20];
const findMaxConsecutiveSum = (arr) => {
  let max_so_far = 0;
  let max_ending_here = 0;
  for (let i = 0; i < arr.length; i++) {
    max_ending_here = Math.max(arr[i], max_ending_here + arr[i]);
    max_so_far = Math.max(max_so_far, max_ending_here)
  }
  return max_so_far;
}
console.log(findMaxConsecutiveSum(myArray));

请注意,重新分配需要max_ending_here调用Math.max和。arr[i]max_ending_here + arr[i]

于 2018-08-25T01:53:23.617 回答
1

据我了解 Kadane 的算法(来自this Wikipedia post),实现它的方式是这样的:

const myArray = [-5, 10, 2, -3, 5, 8, -20];
console.log(myArray.reduce((t, v) => { t.here = Math.max(v, v + t.here);
                                       t.max = Math.max(t.max, t.here); 
                                       return t; },
                           { here : 0, max : 0})['max']);

于 2018-08-25T01:54:54.760 回答