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


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

久了会习惯,不习惯就是原本的比较好。


<<:  样本指纹与模型库中的模板匹配(The sample fingerprint matches the template in the model repository)

>>:  Flutter简介

【Day28】this - call, apply, bind 与严谨模式

call, apply, bind 方法 当我们对函式使用 call, apply, bind 这三...

Day 27 - 不安全的登入机制

出於书本 Chapter 14. Web sites and Application 不安全的登入机...

[经典回顾]过旧的作业系统事故纪录

2018年司法院新闻稿 有关司法院及所属网路遭网军攻击事宜,本院说明如下: 一、事实经过:107年3...

使用 Python 实作网路爬虫 part 3

实际操作 了解 requests 与 BeautifulSoup 的功能後,我们来进行整合吧!接下来...

Day27 - 登出及连线中断

今天来做登出的功能以及连线中断的处理。 Navigation Action 不论是登出还是中断连线,...