[LeetCode] Best Time to Buy and Sell Stock with Cooldown

309. Best Time to Buy and Sell Stock with Cooldown

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

  • new solution update 2022.03.10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size(), res = 0;
int coolDownProfit = 0, prevProfit = 0, sellMax = 0;
for(int i = n - 1; i >= 0; i--) {
int tmp = prevProfit;
prevProfit = max(prevProfit, sellMax - prices[i]);
sellMax = max(sellMax, coolDownProfit + prices[i]);
res = max(res, prevProfit);
coolDownProfit = tmp;
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int dp[5001][2];
int dfs(vector<int>& prices, int i, bool hasStock) {
if(i >= prices.size()) return 0;
if(dp[i][hasStock] != -1) return dp[i][hasStock];
dp[i][hasStock] = 0;
if(hasStock) {
//sell tomorrow or sell today with today's price and cooldown
dp[i][hasStock] = max(dfs(prices, i + 1, hasStock), prices[i] + dfs(prices, i + 2, false));
} else {
//buy tomorrow or buy today with today's price
dp[i][hasStock] = max(dfs(prices, i + 1, hasStock), dfs(prices, i + 1, true) - prices[i]);
}
return dp[i][hasStock];
}
public:
int maxProfit(vector<int>& prices) {
memset(dp, -1, sizeof(dp));
return dfs(prices, 0, false);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/best-time-to-buy-and-sell-stock-with-cooldown/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.