Simple python solution


  • 0
    S
    class Solution(object):
    def maxProfit(self, k, prices):
        """
        :type k: int
        :type prices: List[int]
        :rtype: int
        """
        if not k or not prices: return 0
        if k >= len(prices)/2:
            return sum(i - j for i, j in zip(prices[1:], prices[:-1]) if i - j > 0)
        release=[0]*k
        hold = [float("-inf")]*k
        for price in prices:
            for i in range (k-1, -1, -1):
                release[i] = max(release[i], hold[i]+price)
                if i==0: hold[i] = max(hold[i], -price)
                else: hold[i] = max(hold[i], release[i-1]-price)
        return release[-1]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.