【发布时间】:2020-05-06 09:16:07
【问题描述】:
所以我需要帮助理解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,因为默认情况下我们不赚取任何利润。下一步是我不太确定的:
- 为什么我们将最低价格设置为prices[0]?我认为我们可以使用 min 方法来找到数组的最小值,但它没有给出所需的输出。
现在,我不知道语句的其余部分在做什么。从第一天开始,我们似乎在迭代这些日子,这是我一开始就不明白的事情。
有人能完整、简单地解释一下这个解决方案的工作原理吗?
提前谢谢你!
【问题讨论】:
-
prices.combination(2).max_by{|buy, sell| sell - buy }是另一种选择。
标签: ruby