gpt4 book ai didi

java - 如何返回 Kadane 算法中的最大子数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:37:38 25 4
gpt4 key购买 nike

public class Kadane {
double maxSubarray(double[] a) {
double max_so_far = 0;
double max_ending_here = 0;

for(int i = 0; i < a.length; i++) {
max_ending_here = Math.max(0, max_ending_here + a[i]);
max_so_far = Math.max(max_so_far, max_ending_here);
}
return max_so_far;
}
}

上述代码返回最大子数组的和。

我该如何返回具有最大总和的子数组?

最佳答案

像这样:

public class Kadane {
double[] maxSubarray(double[] a) {
double max_so_far = 0;
double max_ending_here = 0;
int max_start_index = 0;
int startIndex = 0;
int max_end_index = -1;

for(int i = 0; i < a.length; i++) {
if(0 > max_ending_here +a[i]) {
startIndex = i+1;
max_ending_here = 0;
}
else {
max_ending_here += a[i];
}

if(max_ending_here > max_so_far) {
max_so_far = max_ending_here;
max_start_index = startIndex;
max_end_index = i;
}
}

if(max_start_index <= max_end_index) {
return Arrays.copyOfRange(a, max_start_index, max_end_index+1);
}

return null;
}
}

关于java - 如何返回 Kadane 算法中的最大子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7778186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com