首页 > 编程语言 > 详细

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

时间:2015-03-31 10:52:02      阅读:355      评论:0      收藏:0      [点我收藏+]

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]



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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!