Best Time to Buy and Sell Stock with Cooldown

Question

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:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

Tag

  • Dynamic Programming
  • Array

Thought

Reference (This explanation is in Chinese): http://bookshadow.com/weblog/2015/11/24/leetcode-best-time-to-buy-and-sell-stock-with-cooldown/

Since there is cooldown time comparing to Best Time to Buy and Sell Stock II, the recurrence equation need to be edited for considering the cooldown time:

buys[i] means the total profit you can earn when you buy stock at the ith day. sells[i] means the total profit you can earn when you sell stock at the ith day.

delta = prices[i] - prices[i - 1]
sells[i] = max(buys[i - 1] + prices[i], sells[i - 1] + delta) 
buys[i] = max(sells[i - 2] - prices[i], buys[i - 1] - delta)

Code

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        length = len(prices)
        if length < 2:
            return 0
        buys = [None for i in xrange(length)]
        sells = [None for i in xrange(length)]
        buys[0] = -prices[0]
        sells[0] = 0
        for i in xrange(1, length):
            delta = prices[i] - prices[i - 1]
            if i == 1:
                buys[i] = buys[i - 1] - delta
            else:
                buys[i] = max(buys[i - 1] - delta, sells[i - 2] - prices[i])
            sells[i] = max(sells[i - 1] + delta, buys[i - 1] + prices[i])
        return max(sells)

results matching ""

    No results matching ""