動機
用算k個的dp就可以解這題,但是想介紹當初沒有用dp的解法
Problem
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [3,3,5,0,0,3,1,4]Output: 6Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: prices = [1,2,3,4,5]Output: 4Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: prices = [7,6,4,3,1]Output: 0Explanation: In this case, no transaction is done, i.e. max profit = 0.
Example 4:
Input: prices = [1]Output: 0
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 105
Sol
最多只做兩次,所以可以算只做一次的最大與兩次的最大
兩次的最大透過
- 從左看過去到第i天最大的交易
- 從右看過去到第i天最大的交易
相加
# @param {Integer[]} prices
# @return {Integer}
# k = 1
def f(prices)
lowest_price = prices[0]
ans = 0
i = 1
while i < prices.size
lowest_price = [lowest_price,prices[i]].min
ans = [ans, prices[i]-lowest_price].max
i+=1
end
return ans
end
def max_profit(ps)
fore = ps.clone
back = ps.clone
back[-1] = back[0] = 0
fore[-1] = fore[0] = 0
small = ps[0]
(1...ps.size).each do |i|
fore[i] = ps[i]-small > fore[i-1]? ps[i]-small : fore[i-1]
small = [small, ps[i]].min
end
big = ps[-1]
(ps.size-2).downto(1).each do |i|
back[i] = big-ps[i]>back[i+1]? big-ps[i] : back[i+1]
big = [big, ps[i]].max
end
p fore
p back
back.shift
back.push 0
ans = 0
(0...ps.size).each do |i|
ans = [ans, back[i]+fore[i]].max
end
return [ans, f(ps)].max
end