题解 | #买卖股票的最好时机(二)#
买卖股票的最好时机(二)
https://www.nowcoder.com/practice/9e5e3c2603064829b0a0bbfca10594e9
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 计算最大收益
# @param prices int整型一维数组 股票每一天的价格
# @return int整型
#
class Solution:
def maxProfit(self , prices: list[int]) -> int:
# write code here
length = len(prices)
dp =[[0,0] for i in range(length)]
dp[0][0]=0
dp[0][1]=-prices[0]
#分为2种情况,当天手里有股票,和没有股票,有股票可能是前天的或者今天买进的
#没有可能是前天没有,今天也没有买或者前天没有今天买进了股票
for i in range(1,length):
dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i])
dp[i][1]=max(dp[i-1][0]-prices[i],dp[i-1][1])
return max(dp[length-1][0],dp[length-1][1])
查看16道真题和解析