java中的kadane算法
我在 java 中有以下 Kadane 算法的实现。基本上是找到连续子数组的最大和。
String[] numbers = string.split(",");
int max_so_far = 0;
int max_ending_here = 0;
for (int i = 0; i < numbers.length-1;i++){
max_ending_here = max_ending_here + Integer.parseInt(numbers[i]);
if (max_ending_here < 0)
max_ending_here = 0;
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
System.out.println(max_so_far);
但是,如果数组中存在负数和正数的组合,则此方法不起作用,例如以下内容:
2,3,-2,-1,10
应返回 12 作为最大值。截至目前,它返回 5
I have the following implementation of Kadane's algorithm in java. It is basically to find the maximum sum of contiguous subarray.
String[] numbers = string.split(",");
int max_so_far = 0;
int max_ending_here = 0;
for (int i = 0; i < numbers.length-1;i++){
max_ending_here = max_ending_here + Integer.parseInt(numbers[i]);
if (max_ending_here < 0)
max_ending_here = 0;
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
System.out.println(max_so_far);
However this doesn't work if there is a combination of a negative and positive number in an array, for example the following:
2,3,-2,-1,10
Which should return a 12 as a maximum. As of now it returns 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的算法实现看起来不错,但是您的循环条件
i
i
i
i
i
i
i
i
i Numbers.length-1 则不然:它在距数组末尾仅 1 处停止。 <代码>我< numbers.length
应该可以做到:-)You algorithm implementation looks ok, but your loop conditional
i < numbers.length-1
does not: it stops just 1 short of the end of the array.i < numbers.length
should do it :-)这对我有用:
this works for me:
关于 Michał Šrajer 的上述回答:
第 7 行: max_ending_here = Math.max(0, max_ending_here + x);
应该是:
max_ending_here = Math.max(x, max_ending_here + x);
...根据此处定义的 Kadane 算法
Regarding the above answer by Michał Šrajer:
Line #7: max_ending_here = Math.max(0, max_ending_here + x);
should be:
max_ending_here = Math.max(x, max_ending_here + x);
...according to the Kadane algorithm as defined here
为时已晚,但如果将来有人需要的话。
Too late, but if someone needs it in the future.