【问题标题】:Loop isn't recording all solutions into an array循环没有将所有解决方案记录到数组中
【发布时间】: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])

(为格式/易读性而编辑)

【问题讨论】:

    标签: arrays ruby loops


    【解决方案1】:

    index 方法:

    返回 ary 中第一个对象的索引,使得该对象 == 到 obj。

    所以:prices.index(1) 是 0,prices.index(9) 是 1

    如果你使用 index 方法,它没有足够的信息知道选择第二个而不是第一个,所以你得到[0, 1, 0, 1]

    您可以将索引与它一起传递,这样您就可以完全避免这种情况。您还可以存储所有可能的利润和日期,然后在完成后获取最大值。更轻松!这是两个:

    def stock_picker(prices)
      buy_and_sell_days = []
      buy_and_sell_days2 = {}
    
      best_profit = 0
    
      prices.each_with_index do |low, lidx|
        prices.each_with_index do |high, hidx|
          if hidx > lidx
            buy_and_sell_days2[high - low] ||= []
            buy_and_sell_days2[high - low] << [lidx, hidx]
            profit = high - low
            if profit > best_profit
              best_profit = profit
            end
            if high - low == best_profit
              buy_and_sell_days.push(lidx, hidx)
            end
          end
        end
      end
    
      p buy_and_sell_days
      p buy_and_sell_days2
      p buy_and_sell_days2.max_by { |profit, pairs| profit }
      p best_profit
    end
    
    stock_picker([1,9,2,9])
    #> [0, 1, 0, 3]
    #> {8=>[[0, 1], [0, 3]], 1=>[[0, 2]], -7=>[[1, 2]], 0=>[[1, 3]], 7=>[[2, 3]]}
    #> [8, [[0, 1], [0, 3]]]
    #> 8
    

    【讨论】:

    • 好收获。但是在我看来,算法仍然存在问题。它不是捕捉最佳购买解决方案,而只是每个优于或等于当前最佳解决方案的解决方案。例如:stock_picker([1,8,2,9]) 仍然会输出 [0, 1, 0, 3]。
    • 我认为这可能会成为一个问题。我能想到的就是让循环完成并产生一个“best_profit”,然后运行一个单独的循环,使用 best_profit 变量再次搜索数组以查找匹配项。不过这听起来很笨拙,如果可以的话,我真的很想把它保持在一个循环中。
    • 是的,因为只要项目是当前的 best_profit,您就将项目添加到 buy_and_sell_days 数组,但 best_profit 可以更改,因此您从第一个 best_profit 和第二个获得条目。
    • 有几种方法可以剥皮。你可以收集所有的利润和他们的日子,然后抓住最大......
    猜你喜欢
    • 1970-01-01
    • 2016-10-24
    • 2013-12-27
    • 2023-03-25
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多