解题思路:使用动态规划的思想。定义全局收益glob和局部收益local,局部收益即当天已经全部卖出可获得的最大收益。
动态转移方程如下:
diff = prices[i] - prices[i-1]
local[i][j] = max(local[i-1][j]+diff,glob[i-1][j-1]+max(0,diff))
此处分两种情况,i-1天时卖了股票和i-1前已经全部卖出。
glob[i][j] = max(local[i][j],glob[i-1][j])
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
profit = []
i = 0
while(i<len(prices)):
j = i+1
if j == len(prices):
break
if prices[j] > prices[i]:
while j < len(prices)-1 and prices[j+1]>prices[j]:
j += 1
profit.append(prices[j]-prices[i])
i = j
i += 1
ans = 0
if len(profit) <= k:
for p in profit:
ans += p
else:
local = [[0 for i in range(k+1)] for j in range(len(prices))]
glob = [[0 for i in range(k+1)] for j in range(len(prices))]
for i in range(1,len(prices)):
for j in range(1,k+1):
diff = prices[i] - prices[i - 1]
local[i][j] = max(glob[i - 1][j - 1] + max(0,diff), local[i - 1][j] + diff)
glob[i][j] = max(glob[i-1][j],local[i][j])
ans = glob[len(prices)-1][k]
return ans