- 好家伙,这道题还以为有多难呢,吭哧吭哧写了一个晚上加上午,看了答案才知道我想的太复杂了!
- 题目没有要求返回买和卖的时间数,也没有说要手续费,只要把所有上坡的高度都加起来就对了
解法1:把上坡路都加起来
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(len(prices)-1):
if prices[i+1]-prices[i]>0:
profit += prices[i+1]-prices[i]
return profit
解法2:我的方法
class Solution:
def maxProfit(self, prices: List[int]) -> int:
num_day = len(prices)
if num_day == 1:
return 0
else:
p = 0
money = 0
while p<num_day-1:
mai = False
best = -1
sold = 0
for q in range(p+1,num_day):
if prices[q]>prices[p] and best>=0:
if prices[q]<=prices[best]:
sold = best
mai = True
break
else:
best = q
mai = True
elif prices[q]>prices[p] and best<0:
best = q
mai = True
else:
break
if mai:
sold = best
money += prices[sold] - prices[p]
p = sold+1
else:
p += 1
return money
解法3:动态规划,转移矩阵
- d p [ i ] [ 0 ] dp[i][0] dp[i][0]表示在第 i i i天结束的时候,手里没有股票的钱钱数, d p [ i ] [ 1 ] dp[i][1] dp[i][1]则表示手里有股票的钱钱数
-
d
p
[
i
]
[
0
]
dp[i][0]
dp[i][0]的上一情况有两种,一种是
i
−
1
i-1
i−1天时,手里也没有股票,所以第
i
i
i天没有进行交易;
- 还有一种是昨天买入了股票,今天给卖了
- 我们应该取这两种情况中的最大值,即 d p [ i ] [ 0 ] = max { d p [ i − 1 ] [ 0 ] , d p [ i − 1 ] [ 1 ] + p r i c e s [ i ] } dp[i][0]=\max \{dp[i-1][0],dp[i-1][1]+prices[i]\} dp[i][0]=max{dp[i−1][0],dp[i−1][1]+prices[i]}
- 同理, d p [ i ] [ 1 ] dp[i][1] dp[i][1]也有两种情况,表达式为 d p [ i ] [ 1 ] = max { d p [ i − 1 ] [ 1 ] , d p [ i − 1 ] [ 0 ] − p r i c e s [ i ] } dp[i][1]=\max\{dp[i-1][1],dp[i-1][0]-prices[i]\} dp[i][1]=max{dp[i−1][1],dp[i−1][0]−prices[i]}
- 由于在最后一天持有股票的钱钱数肯定小于股票全部抛出的钱钱数,所以只要看 d p [ n − 1 ] [ 0 ] dp[n-1][0] dp[n−1][0]即可
class Solution:
def maxProfit(self, prices: List[int]) -> int:
import numpy as np
dp = np.zeros((2,len(prices)))
dp[0,0] = 0
dp[1,0] = -prices[0]
for i in range(1,len(prices)):
dp[0,i] = max(dp[0,i-1],dp[1,i-1]+prices[i])
dp[1,i] = max(dp[1,i-1],dp[0,i-1]-prices[i])
return int(dp[0,len(prices)-1])
速度太慢,计算了2n次