iT邦幫忙

1

Ruby幼幼班--Best Time to Buy and Sell Stock

  • 分享至 

  • twitterImage
  •  

Yes


Best Time to Buy and Sell Stock

題目連結:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
題目:求得答案是利潤最高值,不是求哪一天。
整理

# @param {Integer[]} prices
# @return {Integer}
def max_profit(prices)

end

puts max_profit([7, 1, 5, 3, 6, 4])  #=>5
puts max_profit([7, 6, 4, 3, 1])  #=>0

求資料內,有一個計算某某值是最極限值,那就用貪心邏輯試看看。

每一天的價錢都有可能是最適合的最低買進與最高賣出。

prices[0] ~ prices[prices.size - 1]

最高價差發生在,當天價錢減去比當天之前的最低價錢中。

def max_profit(prices)
  #買進 => 找到最低的保留住
  #賣出 => 當天價格 = 賣出
  #價差 => 找到最高的保留
  #迴圈
end
  #最低價 = 迴圈中每次的值與預設的最低值相比
  min_price = [min_price, prices[0..prices.size-1].min 
  
  #最高價 = 當天賣價與預設最小買價的差。
  max_profit = [max_profit, (prices[0..prices.size-1] - min)].max

整理

# @param {Integer[]} prices
# @return {Integer}
def max_profit(prices)
  min_price = prices[0] #買價在array中,所以不可能預設指向0。
  max_profit = 0  #檢驗完都是負數,那就是0,所以一開始設定0。
  for i in 0..(prices.size-1)
    min_price = [min_price, prices[i]].min
    max_profit = [max_profit, (prices[i] - min_price)].max
  end
  max_profit
end

改用each

# @param {Integer[]} prices
# @return {Integer}
def max_profit(prices)
  min_price = prices[0]
  max_profit = 0
  prices.each do |price|
    min_price = price if price < min_price
    #min_price = [min_price, price].min  
    max_profit = [max_profit, price - min_price].max  
  end
  max_profit
end

挑自己看得懂的最重要,不過Ruby請選each。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言