Say you have an array for which theithelement is the price of a given stock on dayi.
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)
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int n = prices.length;
// sell[i]: The max profit when we don't have the stock at day i
int[] sell = new int[n];
// buy[i]: The max profit when we have stock at day i
int[] buy = new int[n];
sell[0] = 0;
buy[0] = -prices[0];
for (int i = 1; i < n; i++) {
sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]);
buy[i] = Math.max(buy[i - 1], (i > 1 ? sell[i - 2] : 0) - prices[i]);
}
return sell[n - 1];
}
}
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int curSell = 0;
int preSell = 0;
int buy = -prices[0];
for (int i = 1; i < prices.length; i++) {
int temp = curSell;
curSell = Math.max(curSell, buy + prices[i]);
buy = Math.max(buy, (i > 1 ? preSell : 0) - prices[i]);
preSell = temp;
}
return curSell;
}
}