Best Time to Buy and Sell Stock with Cooldown
Description
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(javascript)
/*
* @lc app=leetcode id=309 lang=javascript
*
* [309] Best Time to Buy and Sell Stock with Cooldown
*/
// @lc code=start
// /** Top-down Approach
// * @param {number[]} prices
// * @return {number}
// */
// const maxProfit = function (prices) {
// const BUY = 0
// const SELL = 1
// const COOL_DOWN = 2
// const memo = []
// const aux = (index, prev) => {
// memo[index] = memo[index] || []
// if (memo[index][prev] !== undefined) {
// return memo[index][prev]
// }
// if (index >= prices.length) {
// return 0
// }
// if (prev === COOL_DOWN) {
// memo[index][prev] = Math.max(
// aux(index + 1, COOL_DOWN),
// -prices[index] + aux(index + 1, BUY),
// )
// } else if (prev === BUY) {
// memo[index][prev] = Math.max(
// aux(index + 1, BUY),
// prices[index] + aux(index + 1, SELL),
// )
// } else {
// memo[index][prev] = aux(index + 1, COOL_DOWN)
// }
// return memo[index][prev]
// }
// return aux(0, COOL_DOWN)
// }
/** Bottom-up Approach
* @param {number[]} prices
* @return {number}
*/
const maxProfit = function (prices) {
const BUY = 0
const SELL = 1
const COOL_DOWN = 2
let prev = [0, 0, 0]
for (let index = prices.length - 1; index >= 0; index--) {
const current = [0, 0, 0]
for (let status = 0; status <= 2; status++) {
if (status === COOL_DOWN) {
current[status] = Math.max(
prev[COOL_DOWN],
-prices[index] + prev[BUY],
)
} else if (status === BUY) {
current[status] = Math.max(
prev[BUY],
prices[index] + prev[SELL],
)
} else {
current[status] = prev[COOL_DOWN]
}
}
prev = current
}
return prev[COOL_DOWN]
}
// @lc code=end