解释购买和出售股票Ruby解决方案的最佳时间
因此,我需要帮助了解leetcode问题的解决方案:解释购买和出售股票Ruby解决方案的最佳时间,ruby,Ruby,因此,我需要帮助了解leetcode问题的解决方案: Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
以下解决方案:
def max_profit(prices)
if prices.size < 2
return 0
else
profit = 0
min_price = prices[0] # set to 2
(1..prices.count-1).each do |k| # number of days
profit = prices[k] - min_price if profit < prices[k] - min_price #profit = 4 - 2 if 2 < 4 - 2
min_price = prices[k] if prices[k] < min_price #4 if 4 < 2
# if 7 < 0
end
return profit
end
end
def最大利润(价格)
如果价格.size<2
返回0
其他的
利润=0
最小价格=价格[0]#设置为2
(1..价格。计数-1)。每个都有多少天
利润=价格[k]-如果利润<价格,则最低价格[k]-如果2<4-2,则最低价格#利润=4-2
最低价格=价格[k]如果价格[k]<最低价格#4如果价格<2
#如果7<0
结束
利润回报
结束
结束
我理解else部分有困难。如果我们一步一步地看,
我们从定义初始值开始。我们将利润的初始值设置为0,因为默认情况下我们没有盈利。下一步是我不太确定的:
提前谢谢你 这个问题的关键是: 您最多只能完成一笔交易 换句话说,任务是: 给出价格列表,按时间顺序找出最低-->最高价格之间的最大差距 例如,给定以下输入:
[5, 11, 6, 2, 5, 3, 10, 1, 4]
然后,最佳解决方案是在价格为2
时买入,然后在价格为10
时卖出。(即使价格达到1
和11
,也无法从一笔交易中获得更大的利润!)
现在,让我们看看代码
第一部分只是一个保护条款:
if prices.size < 2
return 0
如果允许您进行多个事务,那么算法将看起来非常不同。(你应该在价格即将上涨时买进,在价格即将下跌时卖出。)也许你也可以试一试。
prices.composition(2).max_by{buy,sell-buy}
是另一种选择。
[5, 11, 6, 2, 5, 3, 10, 1, 4]
# Day 1: min_price=5, profit=0
# Day 2: min_price=5, profit=6 (Buy at 5 [day 1], sell at 11 [day 2]) -- New Record
# Day 3: min_price=5, profit=6 (Buy at 5 [day 1], sell at 11 [day 2])
# Day 4: min_price=2, profit=6 (Buy at 5 [day 1], sell at 11 [day 2])
# Day 5: min_price=2, profit=6 (Buy at 5 [day 1], sell at 11 [day 2])
# Day 6: min_price=2, profit=6 (Buy at 5 [day 1], sell at 11 [day 2])
# Day 7: min_price=2, profit=8 (Buy at 2 [day 4], sell at 10 [day 7]) -- New Record
# Day 8: min_price=1, profit=8 (Buy at 2 [day 4], sell at 10 [day 7])
# Day 9: min_price=1, profit=8 (Buy at 2 [day 4], sell at 10 [day 7])
# Final result: profit = 8