classSolution(object):defmaxProfit(self, prices):"""
:type prices: List[int]
:rtype: int
"""if prices==[]:return0
res=0
mymin=prices[0]
mymax=prices[0]for i inrange(1,len(prices)):if prices[i]>mymax:
mymax=prices[i]
res=max(res,mymax-mymin)if prices[i]<mymin:
mymax=prices[i]
mymin=prices[i]return res
122. Best Time to Buy and Sell Stock II 在最高价时卖出更新最大最小值
classSolution(object):defmaxProfit(self, prices):"""
:type prices: List[int]
:rtype: int
"""if prices==[]:return0
buy=False
res=0
mymax=mymin=prices[0]for n in prices:if n < mymax:
res+=mymax-mymin
mymax=mymin=n
elif n < mymin:
mymin=mymax=n
elif n > mymax:
mymax=n
res+=mymax-mymin
return res
123. Best Time to Buy and Sell Stock III 只能进行最多两次交易,那么一次从头遍历,一次从尾遍历
classSolution(object):defmaxProfit(self, prices):"""
:type prices: List[int]
:rtype: int
"""#p[i] 0~i 进行一次交易的最大利润 #q[j] j~n 进行一次交易的最大利润
ln =len(prices)if ln<=1:return0
p=[0]*ln
q=[0]*ln
minv=prices[0]for i inrange(1,ln):
minv=min(minv,prices[i])
p[i]=max(p[i-1],prices[i]-minv)
maxv=prices[-1]for j inrange(ln-2,-1,-1):
maxv=max(prices[j],maxv)
q[j]=max(q[j+1],maxv-prices[j])
res=0for i inrange(ln):
res=max(p[i]+q[i],res)return res
188. Best Time to Buy and Sell Stock IV 难题来了,如何设计DP和动态转移方程。
classSolution(object):defmaxProfit(self, k, prices):"""
:type k: int
:type prices: List[int]
:rtype: int
"""
n=len(prices)
res=0if n<2:return0if k>n//2:for i inrange(n-1):if prices[i+1]-prices[i]>0:
res+=prices[i+1]-prices[i]return res
#买入后 或者 卖出后手里的钱
hold=[-2**31]*(k+1)
sold=[0]*(k+1)for price in prices:for j inrange(1,k+1):#要不要持有 只有卖出当前的股票后 才能继续持有新的股票
hold[j]=max(hold[j],sold[j-1]-price)
sold[j]=max(sold[j],hold[j]+price)#要不要卖出 return sold[k]