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

标签 javascript

我正在尝试在 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/

相关文章:

javascript - Vite/Vue 3 : "require is not defined" when using image source as props

javascript - 根据按下的按钮更改要调用的函数

javascript - 构建此字符串的最快方法

javascript - 了解 Firebase 存储 token

javascript - Mapbox GL - 使用 map 样式悬停时切换突出显示特定功能

javascript - 尝试从 React 向 Node 发送 post 请求时出现代理请求错误,代理在 get 请求上工​​作正常

javascript - 这是在我的项目中获取字母表的好方法吗?

带有隐藏函数的 JavaScript 扩展类

javascript - Fluidbox.js 如何与选项卡一起使用

javascript - 如何在 JavaScript 中编写没有 'else' 的 IF else 语句