1,只允许买卖一次
121. Best Time to Buy and Sell Stock
描述
已知几天的价格,规定只准买卖一次,要求实现利润最大化
算法
- 不断迭代,以最低价作为买价
- 进行到当前price时,判断以当前价卖出和历史上最大收益相比哪个收益最大,并返回最大收益
代码
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
minprice = float("inf")
maxprofit = 0
for price in prices:
minprice = min(minprice, price)
profit = price - minprice
maxprofit = max(maxprofit, profit)
return maxprofit
’
‘
2. 需要交易费用(or 有冷却期)的股票交易
1,有一天冷却期的股票交易
描述
已知几天的价格,规定
- 买新股之前要把手里的股出掉
- 卖完之后的一天不允许买卖
算法
- buy[ i ]:第 i 次买股后的总收益,
- s1[ i ]: 与第 i-1次买股相比,第i-1假如不买看哪个收益大,哪个收益大s1就保存哪个
- sell[ i ]: 第 i 次卖股后的总收益
- s2[ i ]:与第 i 次卖股相比,第i次假如不卖看哪个收益大,哪个收益大s1就保存哪个,故而最后的最大收益一定是在s2与sell中
- 有以上分析,可知:
buy[i] = s2[i-1] - prices[i]
s1[i] = max(s1[i-1], buy[i-1])
sell[i] = max(s1[i-1], buy[i-1])+prices[i]
s2[i] = max(s2[i-1],