iT邦幫忙

2

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

Yes


Best Time to Buy and Sell Stock II

這題其實仔細看完內容,會發現比I簡單許多。
題目連結:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
題目重點:買才能賣,當天可以先賣後買。最後一天只有可能是賣。

整理

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

end

puts max_profit([7,1,5,3,6,4])  #=> 7, ans = (5 - 1) + (6 - 3)
puts max_profit([1,2,3,4,5])  #=> 4  這個例子洩漏答案了
puts max_profit([7,6,4,3,1]) #=> 0 

我們把例子2改成比較明顯一點

[1, 5] #=> 最大差4 ,ans = 5 - 1
[1, 3, 5] #=> 最大利潤還是4, ans = 5 - 1 or (3 - 1) + (5 -3)
[1, 4, 3] #=> 最大利潤3 , ans = 4 - 1 ,從中間就會有結果,也不用管第三天的價格了

#所以已經可以求出

總利潤 += 某兩天價格相減  如果 變高的價格 > 買進價格

max_profit += prices[後一天] - prices[買進] if  prices[後一天] > prices[買進]

解答

#這一個會出錯。
def max_profit(prices)
  max_profit = 0
  for i in 0..(prices.size - 1)
    max_profit += (prices[i+1] - prices[i]) if prices[i+1] > prices[i]
  end
  max_profit
end

#錯誤的地方在 if prices[i + 1]這裏,因為如果i是最後一個數字時,prices[i+1]會是nil
#解決方式很多,不一一說明

def max_profit(prices)
  max_profit = 0
  for i in 0...(prices.size - 1)  #這裏
    max_profit += (prices[i+1] - prices[i]) if prices[i+1] > prices[i]
    # prices[i+1] > prices[i] && max_profit += (prices[i+1] - prices[i])
    # 上一句可改寫成這樣,久了會習慣,不習慣就是原本的比較好。
  end
  max_profit
end

2.7.3 :010 > (0..5).to_a
 => [0, 1, 2, 3, 4, 5] 
2.7.3 :011 > (0...5).to_a
 => [0, 1, 2, 3, 4] 

很久沒出現的黑魔法...

2.7.3 :031 > [1, 2, 3, 4, 5].each_cons(1) {|value| p value}
[1]
[2]
[4]
[5]
 => nil 
2.7.3 :032 > [1, 2, 3, 4, 5].each_cons(2) {|value| p value}
[1, 2]
[2, 3]
[3, 4]
[4, 5]
 => nil 
2.7.3 :033 > [1, 2, 3, 4, 5].each_cons(3) {|value| p value}
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
 => nil 

2.7.3 :043 > [1, 2, 3, 4, 5].each_cons(2) {|value, next_value| p [value, next_value]}
[1, 2]
[2, 3]
[3, 4]
[4, 5]
 => nil 

2.7.3 :045 > [1, 2, 3, 4, 5].each_cons(2) {|value, next_value| p next_value - value}
1
1
1
1
 => nil 

改寫答案後

def max_profit(prices)
  max_profit = 0
  prices.each_cons(2) do |price , next_price| 
    next_price > price && max_profit += next_price - price 
  end
  max_profit
end

硬要一行

def max_profit(prices)
  max_profit = 0;prices.each_cons(2){|price , next_price| next_price > price && max_profit += next_price - price};max_profit
end

def max_profit(prices)
  m = 0;prices.each_cons(2){|p, n| n > p && m += n - p};m
end

久了會習慣,不習慣就是原本的比較好。


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

尚未有邦友留言

立即登入留言