方法一 贪心算法
解决这道题,我们应该明白非常重要的一点。以[1,2,3]
为例,我们 在第一天买进,第三天卖出,等价于我们在第一天买进,第二天卖出,第二天再买进,第三天再卖出。
明白了这一点,我们就可以用 贪心算法 来做。我们只要发现第 i
天股票价格低于第 i+1
天的股票价格,就直接买进,第 i+1
天再卖出。
参考代码1
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
参考代码2**
其实也就是看相邻两天的差值(prices[i]-prices[i-1]),如果为正,就可以计入总利润。
所以也可以定义一个差值数组。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
diff = []
for i in range(1, n):
diff.append(prices[i] - prices[i-1])
# 最后一天买入肯定要亏,所以把最后一天买入所获利润记为-1
diff.append(-1)
# diff[i]表示第i天买入第i+1天卖出所获利润
ans = sum([d if d > 0 else 0 for d in diff])
return ans
方法二 递归暴力求解(超时)
感觉这道题暴力比贪心还难想emmmm
虽然超时了,但是这道题还是值得用递归做一下的。
对于第 i
天,我们有三种选择:
- 什么也不做,即不买入,也不卖出;
- 当前不持有股票,并且买入;
- 当前持有股票,并且卖出;
这样我们就会得到一颗二叉树,对应这颗二叉树写代码就可以了。(图源自Liweiwei1419的题解)
参考代码
class Solution:
def maxProfit(self, prices: List[int]) -> int:
def dfs(i, status, profit, n):
if i == n:
self.ans = max(self.ans, profit)
return None
# 1.当前什么也不做
dfs(i+1, status, profit, n)
# 2.当前买入
if status == 0:
dfs(i+1, 1, profit-prices[i], n)
# 3.当前持有股票,卖出
else:
dfs(i+1, 0, profit+prices[i], n)
n = len(prices)
if n < 2:
return 0
self.ans = 0
'''
prices
i :当前是第几天
status: 当前状态 为0表示不持有股票,为1表示持有股票
profit: 当前利润
n: 数组长度
'''
dfs(0, 0, 0, n)
return self.ans