【发布时间】:2018-07-13 14:04:06
【问题描述】:
我被困在一个名为相邻元素产品的函数的算法上,该函数接受一个数组作为参数。它应该返回数组中相邻数字的最大乘积。例如,如果参数是 [2,4,1,3,2,6],由于 2 和 6 的对,它会返回 12。
我的代码是
def adjacentElementsProduct(inputArray)
idx1 = 0
idx2 = 1
while idx2 < inputArray.length
pair = [inputArray[idx1], inputArray[idx1 + 1]]
next_pair = [inputArray[idx2], inputArray[idx2 + 1]]
if next_pair.reduce(:+) > pair.reduce(:+)
pair = next_pair
idx1 += 1
idx2 += 1
else
idx1 += 1
idx2 += 1
end
end
pair.reduce(:+)
end
我只是不知道我的代码在哪里不起作用。我只是在寻找正确的方向,因为我知道仅仅给出答案对我没有多大帮助。谁能帮帮我?
【问题讨论】: