AdSense

Tuesday, June 14, 2016

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:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]


Interestingly, I was looking at a solution online but it turned out it's too hard to understand, so I figured out my own solution, which is also accepted.

The approach is of course DP (just like other 4 problems). We need two helper array, one is for buy, the other is for sell. Each element in the two array represents the maximum profit got making the transaction.

In each day, either we buy the stock or not. The maximum profit will be the profit we got by selling stock two days ago (cool down for one day) and  the profit we got from yesterday (mot buy).

buyMaxProfit[i] = Math.max(sellMaxProfit[i - 2] - prices[i], buyMaxProfit[i - 1]);

In the sell part, we either sell the stock today or not. The maximum profit would be the profit we buy yesterday plus the price of selling the stock today (sell) or the profit we had yesterday (not sell).

sellMaxProfit[i] = Math.max(buyMaxProfit[i] + prices[i], sellMaxProfit[i - 1]);


    public int maxProfit(int[] prices) {
        int len = prices.length;
        if (len < 2) {
            return 0;
        }
        int[] buyMax = new int[len];
        buyMax[0] = -prices[0];
        buyMax[1] = Math.max(-prices[0], -prices[1]);
        int[] sellMax = new int[len];
        sellMax[0] = 0;
        sellMax[1] = Math.max(0, prices[1] - prices[0]);
        
        for (int i = 2; i < len; i++) {
            sellMax[i] = Math.max(buyMax[i - 1] + prices[i], sellMax[i - 1]);
            buyMax[i] = Math.max(sellMax[i - 2] - prices[i], buyMax[i - 1]);
        }
        return sellMax[len - 1];
    }


3 comments:

  1. buyMax[i] = Math.max(sellMax[i - 2] - prices[i], buyMax[i - 1]);

    why did you subtract the price in this statement?

    ReplyDelete