188. Best Time to Buy and Sell Stock IV

188. Best Time to Buy and Sell Stock IV

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        if len(prices)==0:return 0
        k*=2
        s=[float('-inf') for i in range(k)]
        for i in range(len(prices)):
            for j in range(k):
                if j==0:
                    s[j]=max(s[j],-prices[i])
                else:
                    if j%2==1:
                        s[j]=max(s[j],s[j-1]+prices[i])
                    else:
                        s[j]=max(s[j],s[j-1]-prices[i])
        # print(s)
        return max(0,s[k-1])

你可能感兴趣的:(leetcode)