gpt4 book ai didi

arrays - &-> 在 ruby​​ 中是什么意思

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:36:40 25 4
gpt4 key购买 nike

试图理解这个问题的解决方案,但我不知道这个符号是什么意思&->有人可以帮忙吗

# 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

最佳答案

是两个运算符在一起。 -> 创建一个 lambda,& 将其作为 block 传递。

关于arrays - &-> 在 ruby​​ 中是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46161311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com