试图理解这个问题的解决方案,但我不知道这个符号是什么意思& - >可以有人帮忙
# Say you have an array for which the ith element is the price of a given
# stock on day i. Design an algorithm to find the maximum profit. You may
# complete as many transactions as you like (ie, buy one and sell one share
# of the stock multiple times). However, you may not engage in multiple
# transactions at the same time (ie, you must sell the stock before you buy
# again).
def max_profit(prices)
prices.each_cons(2).map(&->(p1, p2){ [p2 - p1, 0].max }).reduce(0, &:+)
end
答案 0 :(得分:3)
这是两个运营商。 ->
创建一个lambda,&
将其作为一个块传递。
答案 1 :(得分:1)
涉及2名运营商:
->
创建lambda
&
将使用Proc
(或lambda
)并将其作为块传递相同的代码可以写成:
prices.each_cons(2).map { |p1, p2| [p2 - p1, 0].max }.reduce(0, &:+)