【问题标题】:find the pair of adjacent elements that has the largest product (incorrect message)找到具有最大乘积的相邻元素对(错误消息)
【发布时间】:2021-11-23 13:39:33
【问题描述】:

我不断收到错误消息,请解释一下有什么问题?

这是一个挑战问题: 给定一个整数数组,找到具有最大乘积的相邻元素对并返回该乘积。 示例

对于inputArray = [3, 6, -2, -5, 7, 3],输出应该是 adjacentElementsProduct(inputArray) = 21.

7 和 3 生产最大的产品。

这是我的代码答案:

function adjacentElementsProduct(inputArray) {
for(let i=0;i<inputArray.length;i++){
    let prod =Math.max(inputArray[i]*inputArray[i+1]);
   

}
 return prod;
}

【问题讨论】:

  • 您好,您的问题是如何解决的?你看到我的回答了吗?我想它可能会对你有所帮助。请给一些反馈。干杯。

标签: javascript arrays function loops


【解决方案1】:

1)你必须得到两个数字的最大值为

sum = Math.max(sum, inputArray[i] * (inputArray[i + 1] ?? 1));

2) 您还必须处理最后一种情况,即i + 1 将是undefined,然后您乘以1。你可以使用null coalescing operator

(inputArray[i + 1] ?? 1)

function adjacentElementsProduct(inputArray) {
  let sum = 0;
  for (let i = 0; i < inputArray.length; i++) {
    sum = Math.max(sum, inputArray[i] * (inputArray[i + 1] ?? 1));
  }
  return sum;
}

const inputArray = [3, 6, -2, -5, 7, 3];
console.log(adjacentElementsProduct(inputArray));

【讨论】:

  • i = 5inputArr[i + 1] 将是 undefined 所以 ??null coalescing 运算符。
  • nullish 合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为 null 或未定义时返回其右侧操作数,否则返回其左侧操作数。
【解决方案2】:

你应该纠正的事情:

  1. 当索引达到inputArray的长度时, inputArray[i+1] 将抛出 OutOfIndex 错误,因为 索引的范围是从0inputArray.length - 1,这里 最后一个 i 的值将是 inputArray.length - 1 然后 i+1 的值将是 inputArray.length,这是不正确的。
  2. 您应该创建一个变量(考虑 max_res)来保存之前的最大结果并将其与新结果进行比较。
  3. for loop 之前定义prod 变量,因为首先在loop 中定义的变量在loop 结束后将无法访问。
  4. 定义一个变量来存储i 的索引,该索引使最大值,因为问题也需要索引。

您应该像这样更改您的代码,以获得正确的输出:

function adjacentElementsProduct(inputArray) {
  let max_res = Number.NEGATIVE_INFINITY;
  let res_index = -1;
  let prod = 0;
  for (let i = 0; i < inputArray.length - 1; i++) {
    prod = Math.max(inputArray[i] * inputArray[i + 1]);  
    if (prod > max_res){
        max_res = prod;
        let res_index = i;
    }
  }
  return prod;
}

let inputArray = [3, 6, -2, -5, 7, 3]
let prod = adjacentElementsProduct(inputArray)

console.log(prod);

【讨论】:

  • 感谢您的解释,但是当我编辑它时,我一直收到不正确的消息,还有另一个错误我无法解决
  • 我更新了我的答案,它现在可以工作了:)
【解决方案3】:

Number.MIN_SAFE_INTEGER 将允许最小整数,因为这需要找到可能包含负整数的最大和。

function solution(inputArray) {
    let largestProduct = Number.MIN_SAFE_INTEGER;
    for (let i = 0; i < inputArray.length; i++) {
        if(inputArray[i] * inputArray[i + 1] > largestProduct) {
            largestProduct = inputArray[i] * inputArray[i + 1];
        }
    }
    return largestProduct;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    相关资源
    最近更新 更多