码迷,mamicode.com
首页 > 编程语言 > 详细

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

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

标签:dp   python   leetcode   

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

标签:dp   python   leetcode   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!