Leetcode[309] Best Time to Buy and Sell Stock with Cooldown
09 Dec 2015###Task1 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]
###Java
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) {
return 0;
}
int[] sells = new int[prices.length];
int[] buys = new int[prices.length];
sells[0] = 0;
sells[1] = Math.max(0, prices[1] - prices[0]);
buys[0] = -prices[0];
buys[1] = Math.max(-prices[0], -prices[1]);
for (int i = 2; i < prices.length; i++) {
sells[i] = Math.max(sells[i - 1], buys[i - 1] + prices[i]);
buys[i] = Math.max(buys[i - 1], sells[i - 2] - prices[i]);
}
return sells[sells.length - 1];
}
}
###Points
-
Maximum –> Still DP
引入辅助数组sells和buys sells[i]表示在第i天不持有股票所能获得的最大累计收益 buys[i]表示在第i天持有股票所能获得的最大累计收益
初始化数组: sells[0] = 0 sells[1] = max(0, prices[1] - prices[0]) buys[0] = -prices[0] buys[1] = max(-prices[0], -prices[1]) 状态转移方程:
sells[i] = max(sells[i - 1], buys[i - 1] + prices[i]) buys[i] = max(buys[i - 1], sells[i - 2] - prices[i]) 所求最大收益为sells[-1]