classSolution(object):defmaxProfit(self, prices):"""
:type prices: List[int]
:rtype: int
"""# 贪心
low =float('inf')
result=0for i inrange(len(prices)):
low =min(low,prices[i])
result =max(result,prices[i]-low)return result
二、DP
classSolution(object):defmaxProfit(self, prices):"""
:type prices: List[int]
:rtype: int
"""# 动态规划# dp[i][0] 表示第i天持有股票所得最多现金# dp[i][1] 表示第i天不持有股票所得最多现金
dp=[[0]*2for i inrange(len(prices))]
dp[0][0]=-prices[0]
dp[0][1]=0for i inrange(1,len(prices)):
dp[i][0]=max(dp[i-1][0],-prices[i])
dp[i][1]=max(dp[i-1][1],dp[i-1][0]+prices[i])returnmax(dp[-1][0],dp[-1][1])
classSolution(object):defmaxProfit(self, prices):"""
:type prices: List[int]
:rtype: int
"""# 贪心:收集每天的正利润
result =0for i inrange(len(prices)-1):if(prices[i+1]-prices[i]>0):
result += prices[i+1]-prices[i]return result