Skip to content

Commit 6b7f97a

Browse files
Create buy_sell_with_cooldown_dp.cpp
1 parent b656113 commit 6b7f97a

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

buy_sell_with_cooldown_dp.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
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+
};

0 commit comments

Comments
 (0)