动态规划: dp定义为在第i天有无持有股票的最大收益
base dp[0][0] = 0 , dp[0][1]=-price[0]
转移方程: dp[i][0] = max(前一天就没持有,前一天持有了今天卖了)
dp[i][1] = max(前一天就持有, 前一天没持有今天买了)
可以压缩一下优化空间复杂度
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
#dp定义为在第i天有无持有股票的最大收益
#base dp[0][0] = 0 , dp[0][1]=-price[0]
n = len(prices)
dp = [[0]*2 for i in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for i in range(1,n):
dp[i][0] = max(dp[i-1][0],dp[i-1][1]+prices[i])
dp[i][1] = max(dp[i-1][1],dp[i-1][0]-prices[i])
return dp[n-1][0]
无限次买卖可以只买上涨的时候,题目说同一天不准交易两次应该是不推荐这种解法
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
res = 0
for i in range(1,n):
if prices[i] > prices[i-1]:
res += prices[i] - prices[i-1]
return res