如何将每个值乘以其他值

How to multiply each value by each other value

我想取数组中的每一项,将它们相乘,然后求乘数的最大值。

我尝试了很多东西,直到找到 cycle 方法,然后得到了这个,现在卡住了:

def adjacentElementsProduct(inputArray)
  outArray = inputArray.cycle(inputArray.length){|num| num[0] * num[1]}.to_a

  return outArray.max
end

这是行不通的,因为 Ruby 显然没有(声明的)能力知道 num[0]num[1] 是什么。

例如:

adjacentElementsProduct([3, 6, -2, -5, 7, 3]) => 21 

因为3*7是所有数字相乘的最大乘积。

您可以找到两个最大值。无需尝试每种组合:

[3, 6, -2, -5, 7, 3].max(2).inject(:*)
#=> 42

如果您仍想使用组合,请使用 combination 方法:

[3, 6, -2, -5, 7, 3].combination(2)
                    .map { |f, s| f * s }
                    .max
#=> 42

如果你想找到最大的一对一值,使用each_cons:

[3, 6, -2, -5, 7, 3].each_cons(2)
                    .map {|f, s| f * s }
                    .max
#=> 21

此外,

max_by {|f, s| f * s }.inject(:*)

也可以使用,但这取决于您。