买卖股票的最佳时机
买卖一次
动态规划,记录每一次买卖的值
def maxProfit(self, prices: List[int]) -> int:
first_buy = - prices[0];
frist_sell = 0;
for i in range(1,len(prices)):
#第一次购买价值
first_buy = max(first_buy,-prices[i])
#第一次卖的价值
frist_sell = max(frist_sell,prices[i] + first_buy)
return frist_sell
优化方程,最大价值dp[i] = price[i] - min
def maxProfit(self, prices: List[int]) -> int:
min = prices[0]
res = 0
for i in range(1,len(prices)):
if prices[i] < min:
min = prices[i]
else:
value = prices[i] - min
if res < value:
res = value
return res
多次买卖
数论,低买高卖
def maxProfit(self, prices: List[int]) -> int:
res = 0;
for i in range(len(prices)-1):
if(prices[i] < prices[i+1]):
res += prices[i+1] - prices[i]
return res
两次依次买卖
第二买卖的值要基于第一次的卖出的价值
def maxProfit(self, prices: List[int]) -> int:
first_buy = second_buy = - prices[0];
frist_sell = second_sell = 0;
for i in range(1,len(prices)):
#第一次购买价值
first_buy = max(first_buy,-prices[i])
#第一次卖的价值
frist_sell = max(frist_sell,prices[i] + first_buy)
#第二次买的价值
second_buy = max(second_buy,frist_sell - prices[i])
#第二次卖的值
second_sell = max(second_sell,prices[i] + second_buy)
return second_sell
K次买卖
数组记录每次价值
def maxProfit(self, k: int, prices: List[int]) -> int:
if len(prices) == 0 or k == 0:
return 0
buys = [-prices[0] for i in range(k)]
sells = [0 for i in range(k)]
for i in range(len(prices)):
pre_sell = 0;
for j in range(k):
buys[j] = max(buys[j],pre_sell - prices[i])
pre_sell = sells[j] = max(sells[j],prices[i] + buys[j])
return sells[k-1];