classSolution:defmaxProfit(self,k:int,prices: List[int]) ->int: n =len(prices)if n <2:return0if k > n //2:# 因为一次交易至少占用两天, 所以如果`k`大于天数的一般, 等同于无限次交易, 不需要再分k次, 防止OOM bear, hold =0,-prices[0]for i inrange(1, n): old_hold = hold hold =max(old_hold, bear - prices[i]) bear =max(bear, old_hold + prices[i])return bearelse: bear = [[0] * n for _ inrange(k +1)] hold = [[0] * n for _ inrange(k +1)]for t in hold: t[0]=-prices[0]for i inrange(1, n):for tk inrange(1, k +1): hold[tk][i] =max(hold[tk][i -1], bear[tk -1][i -1] - prices[i]) bear[tk][i] =max(bear[tk][i -1], hold[tk][i -1] + prices[i])returnmax([t[-1] for t in bear])