贪心:左边取最小 右边取最大
class Solution:
def maxProfit(self, prices: List[int]) -> int:
low=float('inf')
res=0
for i in range(len(prices)):
low=min(low,prices[i])
res=max(res,prices[i]-low)
return res
因为只能买卖一次,开头一定是-price,结尾一定要卖出去
因为i只与i-1相关,还可以用滚动2维数组,用i%2来省空间
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 每天两个状态 还有和没有的收益
if not prices: return 0
dp=[[0]*2 for _ in range(len(prices))]
dp[0][0]=-prices[0]
dp[0][1]=0
for i in range(1,len(prices)):
dp[i][0]=max(dp[i-1][0],-prices[i])
dp[i][1]=max(dp[i-1][1],prices[i]+dp[i-1][0])
return dp[-1][1]
122. 买卖股票的最佳时机 II
之前用贪心做过,赚了就卖
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res=0
for i in range(1,len(prices)):
res+=max(prices[i]-prices[i-1],0)
return res
动归和上面思路一样,就是-price要加入前面的利润
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices: return 0
dp=[[0]*2 for _ in range(2)]
dp[0][0]=-prices[0]
dp[0][1]=0
for i in range(1,len(prices)):
dp[i%2][0]=max(dp[(i-1)%2][0],dp[(i-1)%2][1]-prices[i])
dp[i%2][1]=max(dp[(i-1)%2][1],dp[(i-1)%2][0]+prices[i])
return dp[(len(prices)-1)%2][1]