leetcode-188-Best Time to Buy and Sell Stock IV-动态规划

题目: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/#/description

1.题意

还是一只股票的n天的价格, 最多交易k次(一买一卖算一次), 能获得的最大利润是多少?

2.思路

用动态规划, dp[i][j] 表示前j天最多交易i次的最大利润, 那么答案就是dp[k][n].

每天智能做三种事情, 啥也不干 ;买进; 卖出,
dp[i][j] = max(dp[i][j-1], prices[j] + tmpMax);,即max(啥也不干, 卖出)
tmpMax = max(tmpMax, dp[i-1][j-1] - prices[j]);, 即 max(tmpMax, 买入)

3.代码

#ac
class Solution(object):
    def maxProfit(self, k, prices):
        """
        :type k: int
        :type prices: List[int]
        :rtype: int
        """
        #dp[i][j] means the max profit when transaction <= i and within first j days 
        days=len(prices)
        if(k>=days/2):
            return self.fun_greedy(prices)
        else:
            return self.fun_dp(k, prices)

    def create2dArr(self,rowNum,columnNum):
        arr = [[0]*columnNum for i in range(rowNum)]
        return arr

    def fun_dp(self,k,prices):
            """
            :type k: int
            :type prices: List[int]
            :rtype: int
            """
            #dp[i][j] means the max profit when transaction <= i and within first j days 
            days=len(prices)
            dp=self.create2dArr(k+1, days)
            for i in range(1,k+1):
                tmpMax=dp[i-1][0]-prices[0]
                for j in range(1,days):
                    dp[i][j] = max(dp[i][j-1],  prices[j] + tmpMax);
                    tmpMax = max(tmpMax, dp[i-1][j-1] - prices[j]);
            return dp[k][days-1];

    def fun_greedy(self,prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            answer=0
            for i in range(len(prices)-1):
                delta=prices[i+1]-prices[i]
                answer=answer+delta if delta>0 else answer;
            return answer;

4. 测试用例

print Solution().maxProfit(2, [1,2 ,3, 5, 6, 1, 7])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值