【问题标题】:Explanation for Best Time to Buy and Sell Stock Ruby Solution最佳买卖股票红宝石解决方案的说明
【发布时间】: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,因为默认情况下我们不赚取任何利润。下一步是我不太确定的:

  1. 为什么我们将最低价格设置为prices[0]?我认为我们可以使用 min 方法来找到数组的最小值,但它没有给出所需的输出。

现在,我不知道语句的其余部分在做什么。从第一天开始,我们似乎在迭代这些日子,这是我一开始就不明白的事情。

有人能完整、简单地解释一下这个解决方案的工作原理吗?

提前谢谢你!

【问题讨论】:

  • prices.combination(2).max_by{|buy, sell| sell - buy } 是另一种选择。

标签: ruby


【解决方案1】:

这个问题的关键是:

您最多只能完成一个交易

也就是说,任务是:

给定一个价格列表,找出最低-->最高价格之间的最大时间间隔

例如,给定以下输入:

[5, 11, 6, 2, 5, 3, 10, 1, 4]

那么最优方案是在价格为2 时买入,然后在价格为10 时卖出。 (即使价格确实达到了111,也没有办法从一笔交易中获得更大的利润!)

那么现在,让我们看一下代码。

第一部分只是一个保护子句:

if prices.size < 2
  return 0

“如果只有一个价格,那是不可能盈利的。返回0。”

然后算法的其余部分如下工作:

  1. “截至今天的最低价格”设置为min_price。 (因为如果您在未来的任何时候卖出,那么这一定是买入的最佳时机。)
  2. 逐步完成每一天。如果您在那天卖出,您将获得的利润是:prices[k] - min_price。如果这是一条“新记录”,则将该值存储为更新后的profit
  3. 检查这是否是新的最低购买价格 (prices[k] &lt; 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

如果允许您进行多笔交易,那么算法看起来会大不相同。 (你应该在价格即将上涨时买入,在价格即将下跌时卖出。)也许你也可以尝试一下。

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2020-10-04
    • 2018-03-20
    • 2017-09-26
    • 1970-01-01
    相关资源
    最近更新 更多