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

题目如下:

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])

 

posted @ 2019-03-22 14:27  seyjs  阅读(175)  评论(0编辑  收藏  举报