題目
給定一個(gè)數(shù)組,它的第 i 個(gè)元素是一支給定股票第 i 天的價(jià)格嚷兔。
設(shè)計(jì)一個(gè)算法來(lái)計(jì)算你所能獲取的最大利潤(rùn)。你可以盡可能地完成更多的交易(多次買(mǎi)賣(mài)一支股票)。
注意:你不能同時(shí)參與多筆交易(你必須在再次購(gòu)買(mǎi)前出售掉之前的股票)俱两。
示例 1:
輸入: [7,1,5,3,6,4]
輸出: 7
解釋: 在第 2 天(股票價(jià)格 = 1)的時(shí)候買(mǎi)入,在第 3 天(股票價(jià)格 = 5)的時(shí)候賣(mài)出, 這筆交易所能獲得利潤(rùn) = 5-1 = 4 曹步。
隨后宪彩,在第 4 天(股票價(jià)格 = 3)的時(shí)候買(mǎi)入,在第 5 天(股票價(jià)格 = 6)的時(shí)候賣(mài)出, 這筆交易所能獲得利潤(rùn) = 6-3 = 3 讲婚。
示例 2:
輸入: [1,2,3,4,5]
輸出: 4
解釋: 在第 1 天(股票價(jià)格 = 1)的時(shí)候買(mǎi)入尿孔,在第 5 天 (股票價(jià)格 = 5)的時(shí)候賣(mài)出, 這筆交易所能獲得利潤(rùn) = 5-1 = 4 。
注意你不能在第 1 天和第 2 天接連購(gòu)買(mǎi)股票筹麸,之后再將它們賣(mài)出活合。
因?yàn)檫@樣屬于同時(shí)參與了多筆交易,你必須在再次購(gòu)買(mǎi)前出售掉之前的股票物赶。
示例 3:
輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒(méi)有交易完成, 所以最大利潤(rùn)為 0白指。
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán)酵紫,非商業(yè)轉(zhuǎn)載請(qǐng)注明出處侵续。
解答
解法一(暴力解法)
- 確定買(mǎi)入點(diǎn)倔丈、賣(mài)出點(diǎn),如果還有機(jī)會(huì)状蜗,重復(fù)執(zhí)行前面步驟
- 每個(gè)買(mǎi)入需五、賣(mài)出點(diǎn)對(duì)應(yīng)一次利潤(rùn),如果下一個(gè)買(mǎi)入轧坎、賣(mài)出點(diǎn)利潤(rùn)更高則替換
-
本方法使用了遞歸
image.png
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit = 0
p_len = len(prices)
for buy in xrange(p_len-1):
for sale in xrange(buy+1,p_len):
if sale_cache.get((buy, sale)) !=None:
return sale_cache.get((buy, sale))
sale_price = prices[sale]
buy_price = prices[buy]
if sale_price <= buy_price:
continue
profit = sale_price - buy_price
if p_len - sale > 2:
profit += self.maxProfit(prices[sale+1:])
max_profit = profit if profit > max_profit else max_profit
return max_profit
解法二
最大利潤(rùn)需要關(guān)注連續(xù)的波峰波谷:
在連續(xù)的波峰波谷買(mǎi)入賣(mài)出將獲得最大利潤(rùn)宏邮,如果跳過(guò)一個(gè)波峰,可能導(dǎo)致利潤(rùn)降低缸血。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
i = 0
max_profit = 0
p_len = len(prices)
while i < p_len-1:
# 找波谷
while i < p_len-1 and prices[i] >= prices[i+1]:
i +=1
vally = prices[i]
# 找波峰
while i < p_len-1 and prices[i] <= prices[i+1]:
i +=1
peak = prices[i]
max_profit += peak-vally
return max_profit