Best Time to Buy and Sell Stock with Cooldown

LeetCode Q 123 - 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]

Solution : DP

We can use 4 varaibles to represent the transaction states until day i. They are buy, sell, hold, cooldown. Their relationship is shown as follows.

Code: Version 1

public int maxProfit(int[] prices) {
	if (prices == null || prices.length == 0) return 0;

	int buy = -prices[0], hold = -prices[0];
	int sell = 0, cooldown = 0;
	
	for (int price: prices) {
		int orig_hold = hold, orig_sell = sell;
		hold = Math.max(hold, buy);
		sell = Math.max(buy, orig_hold) + price;
		buy = cooldown - price;
		cooldown = Math.max(cooldown, orig_sell);
	}

	return Math.max(sell, cooldown);
}

Code: Version 2

public int maxProfit(int[] prices) {
	if (prices == null || prices.length == 0) return 0;

	int buy = Integer.MIN_VALUE, hold = Integer.MIN_VALUE;
	int sell = 0, cooldown = 0;
	
	for (int price: prices) {
		int ori_buy = buy, ori_sell = sell;
		buy = cooldown - price;
		sell = Math.max(ori_buy, hold) + price;
		hold = Math.max(ori_buy, hold);
		cooldown = Math.max(cooldown, ori_sell);
	}

	return Math.max(sell, cooldown);
}

   Reprint policy


《Best Time to Buy and Sell Stock with Cooldown》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC