【发布时间】:2015-10-12 21:28:10
【问题描述】:
此循环搜索stock_picker 变量,并通过检查哪两天的净利润最高来确定哪两天是最好的“买入”和“卖出”天。循环正确地看到,在第 0 天买入并在第 1 天卖出,我的最大利润将是 8。
但是,我希望程序将所有可能的最佳买卖日期记录到一个数组中。如果我在第 0 天买入并在第 3 天卖出,我的利润仍然是 8,但程序没有记录这一点。相反,它返回一个 [0,1,0,1] 数组,告诉我它看到了两个解决方案,但由于某种原因没有记录第二个解决方案。如何返回 [0,1,0,3] 的数组?
def stock_picker(prices)
buy_and_sell_days = []
best_profit = 0
prices.each do |low|
prices.each do |high|
if prices.index(high) > prices.index(low)
profit = high - low
if profit > best_profit
best_profit = profit
end
if high - low == best_profit
buy_and_sell_days.push(prices.index(low), prices.index(high))
end
end
end
end
p buy_and_sell_days
p best_profit
end
stock_picker([1, 9, 2, 9])
(为格式/易读性而编辑)
【问题讨论】: