Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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]

My code:

class Solution(object):
    def maxProfit1(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices)==0:
            return 0
        self.record=[-1]*len(prices)
        max_profit=self.check_profit(prices,0,0,True)
        
        return max_profit
    def check_profit(self,prices,i,hold_number,buy_flag):
        if i==len(prices):
            return 0
        
        profit_sell=-99999999
        if hold_number>=1:
            profit1=self.check_profit(prices,i+1,hold_number-1,False)#Sell at i-th
            profit_sell=profit1+prices[i]
        profit_buy=-99999999
        if buy_flag:
            profit1=self.check_profit(prices,i+1,hold_number+1,True)#Buy at i-th
            profit_buy=profit1-prices[i]
        profit_cool=self.check_profit(prices,i+1,hold_number,True)
        self.record[i]=max([profit_sell,profit_buy,profit_cool])
        print('For %d th operation, sell %d, buy %d, cool %d'%(i,profit_sell,profit_buy,profit_cool))
        return self.record[i]
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        sell = [0] * len(prices)
        buy = [0] * len(prices)
        buy[0] = -prices[0]
        
        for i in range(1, len(prices)):
            sell[i] = max(buy[i - 1] + prices[i], sell[i - 1])
            buy[i] = max(buy[i - 1], sell[i - 2] - prices[i])
        
        return sell[-1]
        

Solution: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/