当前位置:首页 > Python教程 > python技巧

188. Best Time to Buy and Sell Stock IV Leetcode Python

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Based on Dynamic planning 

maintain two vectors: gpro: to day i the maximum profit

               lpro: to day i the maximum profit with jth sell by day i

the complexity of this problem is O(k*n)

code is as follow:

class Solution:
    # @return an integer as the maximum profit 
    def helper(self, prices):
        pro = 0
        for i in range(len(prices) - 1):
            pro = max(pro, pro + prices[i+1] - prices[i])
        return pro
    def maxProfit(self, k, prices):
        m = len(prices)
        if m == 0:
            return 0
        if k >= m:### if k >=m this problem become best time to sell II
            return self.helper(prices)
        lpro = [0] * (k + 1)
        gpro = [0] * (k + 1)
        for i in range(len(prices) - 1):
            dif = prices[i + 1] - prices[i]
            j = k
            while j >= 1:
                lpro[j] = max(gpro[j-1]+max(0,dif), lpro[j] + dif)
                gpro[j] = max(gpro[j], lpro[j])
                j-=1
        return gpro[k]



原文:http://blog.csdn.net/hyperbolechi/article/details/44774971


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!