gpt4 book ai didi

javascript - Codewars Kata 的问题 - 增加数组的最大差异

转载 作者:行者123 更新时间:2023-11-29 20:27:07 26 4
gpt4 key购买 nike

我正在尝试在 Codewars 上解决这个 Kata:https://www.codewars.com/kata/largest-difference-in-increasing-indexes/train/javascript

Consider all of the pairs of numbers in the array where the first one is less than or equal to the second one.

From these, find a pair where their positions in the array are farthest apart.

Return the difference between the indexes of the two array elements in this pair.

这是我所拥有的,但无法弄清楚为什么它不正确。

var largestDifference = function(data) {
arr = [];
for (var i = 0; i < data.length-1; i++) {
for (var j = data.length-1; j>i; j--) {
if (data[i] <= data[j]) {
arr.push(i)
}
}
}
ans = Math.max(...arr)- Math.min(...arr);
return ans
};

最佳答案

您不需要将 i 插入 ans 数组。您需要推送 ji 的区别,即 j - i

var largestDifference = function(data) {
let res = [];
for(let i = 0; i < data.length; i++){
for(let j = i + 1; j < data.length; j++){
if(data[i] <= data[j]){
res.push(j - i);
}
}
}
return res.length ? Math.max(...res) : 0
};
console.log(largestDifference([9,4,1,10,3,4,0,-1,-2])) // 4
console.log(largestDifference([3, 2, 1])) // 0

关于javascript - Codewars Kata 的问题 - 增加数组的最大差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59052986/

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