面试经典(7/150)买卖股票的最佳时机2
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。
你也可以先购买,然后在 同一天 出售。
解题思路
可以使用动态规划来解决这个问题。定义两个状态变量,buy 和 sell,
分别表示在第 i 天持有股票和不持有股票时的最大利润。
然后,根据当前的股票价格和前一天的状态来更新这两个变量。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
n = len(prices)
buy = -prices[0]#初始状态,第一天不持有股票
sell = 0
for i in range(1,n):
#计算在第i天持有股票和不持有股票的最大利润
buy = max(buy, sell-prices[i])
sell = max(sell, buy+prices[i])
return sell