【leetcode】309. Best Time to Buy and Sell Stock with Cooldown

博客围绕股票买卖问题展开,给定数组表示每日股票价格,要求设计算法求最大利润,可多次交易但有不能同时多笔交易和卖出后有1天冷却期的限制。与有交易手续费的题目对比,修改了状态转移方程,并给出了相关代码来源。

题目如下:

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]

题目如下:本题和 【leetcode】714. Best Time to Buy and Sell Stock with Transaction Fee 几乎是一样的,一个是有交易手续费,一个是有CD时间。在【leetcode】714. Best Time to Buy and Sell Stock with Transaction Fee 的基础上,dp[i][0] (跳过) 和dp[i][2]出售都是一样的,不同之处在于dp[i][1] ,这里有至少一天的CD,所以修改状态状态转移方程为:dp[i][1] = max(dp[i][1], -prices[i], dp[j][2] - prices[i]) (这里i > 2,j < i-1 ),而在i = 2的时候,就只有 dp[i][1] = max(dp[i][1], -prices[i])。

代码如下:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) <= 1:
            return 0
        elif len(prices) == 2:
            return max(0, prices[1] - prices[0])
        dp = []
        for i in prices:
            dp.append([-float('inf'),-float('inf'),-float('inf')])  #0:do nothing, 1:buy ,2:sell
        dp[0][1] = -prices[0]
        dp[1][1] = -prices[1]
        dp[1][2] = prices[1] - prices[0]

        max_buy = max(dp[0][1],dp[1][1])
        max_sell = dp[1][2]
        for i in range(2,len(dp)):
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1], dp[i - 1][2])
            dp[i][2] = max(dp[i][2], max_buy + prices[i])
            if i == 2: # the 3rd day can but stocks only there are no transactions in the first two days
                dp[i][1] = max(dp[i][1], -prices[i])
            else:
                dp[i][1] = max(dp[i][1], -prices[i], max_sell - prices[i])
            max_sell = max(max_sell, dp[i-1][2]) #cooldown day,so update max_sell in i-1 day
            max_buy = max(max_buy, dp[i][1])

            '''
            for j in range(i):
                if j != i-1: #cooldown day
                    dp[i][1] = max(dp[i][1],-prices[i],dp[j][2] - prices[i])
                dp[i][2] = max(dp[i][2],dp[j][1] + prices[i])
            '''

        #print dp
        return max(0,dp[-1][0],dp[-1][2])

 

转载于:https://www.cnblogs.com/seyjs/p/10578031.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值