所以我需要帮助来了解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 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
我无法理解else部分。如果我们逐步进行, 我们首先定义初始值。由于默认情况下我们没有任何利润,因此我们将利润的初始值设置为0。下一步是我不太确定的事情:
现在,我不知道语句其余部分在做什么。从第一天开始,似乎我们就在迭代这些日子,这是我一开始并不了解的事情。
有人会对此解决方案进行完整而简单的解释吗?
提前谢谢!
答案 0 :(得分:2)
这个问题的关键是:
只允许您完成最多一项交易
换句话说,任务是:
给出价格列表,找到最低价格->最高价格之间的最大时间顺序
例如,给定以下输入:
[5, 11, 6, 2, 5, 3, 10, 1, 4]
然后,最佳解决方案是在价格为2
时购买,然后在价格为10
时出售。 (即使价格确实达到了1
和11
,也无法通过一笔交易获得更大的利润!)
现在,让我们看一下代码。
第一部分只是一个保护子句:
if prices.size < 2
return 0
“如果只有一个价格,那就不可能获利。返回0
。”
其余算法如下:
min_price
。 (因为如果您在将来的任何时候出售,那么这肯定是购买的最佳时间。)prices[k] - min_price
。如果这是“新记录”,则将值存储为更新的profit
。prices[k] < min_price
)。如果是这样,则将min_price
更新为当天的价格。让我们以上面的输入为例:
[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
如果允许您进行多次交易,则该算法看起来会非常不同。 (您应该在价格上涨时就买入,而在价格下跌时就卖出。)也许您也可以尝试一下。