Skip to content

Commit 1f5946d

Browse files
Update buy_sell_with_cooldown_dp.cpp
1 parent 661ed86 commit 1f5946d

File tree

1 file changed

+45
-11
lines changed

1 file changed

+45
-11
lines changed

buy_sell_with_cooldown_dp.cpp

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,53 @@
1-
//fsm based solution
1+
// //fsm based solution
2+
3+
// class Solution {
4+
// private:
5+
// const int STATE_NUM = 3, STEP_NUM = 2, S_BUY = 0, S_SELL = 1, S_COOL = 2;
6+
// public:
7+
// int maxProfit(vector<int>& prices) {
8+
// int state[STATE_NUM][STEP_NUM], i, j, steps = prices.size(),cur = 0, next = 1;
9+
10+
// fill_n(&state[0][0], STATE_NUM*STEP_NUM, INT_MIN);
11+
12+
// for(i=0,state[0][0]=0;i<steps;++i, swap(cur, next)) {
13+
// state[S_BUY][next] = max(state[S_BUY][cur], state[S_COOL][cur]);
14+
// state[S_SELL][next] = max(state[S_BUY][cur]-prices[i], state[S_SELL][cur]);
15+
// state[S_COOL][next] = state[S_SELL][cur] + prices[i];
16+
// }
17+
// return max(state[S_BUY][cur], state[S_COOL][cur]);
18+
// }
19+
// };
20+
221

322
class Solution {
4-
private:
5-
const int STATE_NUM = 3, STEP_NUM = 2, S_BUY = 0, S_SELL = 1, S_COOL = 2;
623
public:
7-
int maxProfit(vector<int>& prices) {
8-
int state[STATE_NUM][STEP_NUM], i, j, steps = prices.size(),cur = 0, next = 1;
24+
25+
int dp[50001][2][2];
26+
int solve(vector<int> &prices, int cool, int own, int index) {
927

10-
fill_n(&state[0][0], STATE_NUM*STEP_NUM, INT_MIN);
28+
//basecase
29+
if(index == prices.size())
30+
return 0;
1131

12-
for(i=0,state[0][0]=0;i<steps;++i, swap(cur, next)) {
13-
state[S_BUY][next] = max(state[S_BUY][cur], state[S_COOL][cur]);
14-
state[S_SELL][next] = max(state[S_BUY][cur]-prices[i], state[S_SELL][cur]);
15-
state[S_COOL][next] = state[S_SELL][cur] + prices[i];
32+
if(dp[index][own][cool] != -1)
33+
return dp[index][own][cool];
34+
35+
if(own) {
36+
int case1 = prices[index] + solve(prices, 1, 0, index + 1);
37+
int case2 = solve(prices, 0, 1, index + 1);
38+
return dp[index][own][cool] = max(case1, case2);
1639
}
17-
return max(state[S_BUY][cur], state[S_COOL][cur]);
40+
41+
else {
42+
int case1 = (cool == 1) ? 0 : (-prices[index] + solve(prices, 0, 1, index + 1));
43+
int case2 = solve(prices, 0, 0, index + 1);
44+
return dp[index][own][cool] = max(case1, case2);
45+
}
46+
}
47+
48+
int maxProfit(vector<int>& prices) {
49+
memset(dp, -1, sizeof dp);
50+
return solve(prices, 0, 0, 0);
51+
1852
}
1953
};

0 commit comments

Comments
 (0)