|
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 | + |
2 | 21 |
|
3 | 22 | class Solution {
|
4 |
| -private: |
5 |
| - const int STATE_NUM = 3, STEP_NUM = 2, S_BUY = 0, S_SELL = 1, S_COOL = 2; |
6 | 23 | 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) { |
9 | 27 |
|
10 |
| - fill_n(&state[0][0], STATE_NUM*STEP_NUM, INT_MIN); |
| 28 | + //basecase |
| 29 | + if(index == prices.size()) |
| 30 | + return 0; |
11 | 31 |
|
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); |
16 | 39 | }
|
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 | + |
18 | 52 | }
|
19 | 53 | };
|
0 commit comments