122. 买卖股票的最佳时机 II
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/comments/87652
第一种方法:深度优先搜索,时间复杂度O(2^n),这个通过不了LeetCode,不过能work,测试了多组测试样例是正确的
class Solution:
def maxProfit(self, prices: List[int]) -> int:
self.prices = prices
self.profit = []
self.helper(0, 0, 0)
return max(self.profit)
# have 0:未持有 1:持有
def helper(self, i, have, profit):
if i == len(self.prices):
self.profit.append(profit)
return
if have: # 如果持有中
self.helper(i+1, 0, profit + self.prices[i]) # 卖出
self.helper(i+1, 1, profit) # 不动
else: # 如果未持有
self.helper(i+1, 0, profit) # 不动
self.helper(i+1, 1, profit - self.prices[i]) # 买入
第二种方法:贪心算法,一次遍历,只要今天价格小于明天价格就在今天买入然后明天卖出,时间复杂度O(n)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
ans = 0
for i in range(1, len(prices)):
if prices[i] > prices[i-1]:
ans += prices[i] - prices[i-1]
return ans
第三种方法:DP动态规划,第i天只有两种状态,不持有或持有股票,当天不持有股票的状态可能来自昨天卖出或者昨天也不持有,同理,当天持有股票的状态可能来自昨天买入或者昨天也持有中,取最后一天的不持有股票状态就是问题的解
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
n = len(prices)
dp = [[0]*2 for _ in range(n)]
# dp[i][0]表示第i天不持有股票, dp[i][1]表示第i天持有股票
dp[0][0], dp[0][1] = 0, - 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]