-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBest Time to Buy and Sell Stock II
65 lines (59 loc) · 2.01 KB
/
Best Time to Buy and Sell Stock II
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
public:
int solve(int index, int buy, vector<int>& prices, vector<vector<int>>& dp){
if(index == prices.size()){
return 0;
}
if(dp[index][buy] != -1){
return dp[index][buy];
}
int profit = 0;
if(buy){
profit = max((-prices[index] + solve(index+1, 0, prices, dp)), (0 + solve(index + 1, 1, prices, dp)));
}
else{
profit = max((prices[index] + solve(index+1, 1, prices, dp)), (0 + solve(index + 1, 0, prices, dp)));
}
return dp[index][buy] = profit;
}
int solveTab(vector<int>& prices){
vector<vector<int>> dp(prices.size()+1, vector<int>(2, 0));
for(int index = prices.size()-1; index >= 0; index--){
for(int buy = 0; buy <= 1; buy++){
int profit = 0;
if(buy){
profit = max((-prices[index] + dp[index+1][0]), (0 + dp[index+1][1]));
}
else{
profit = max((prices[index] + dp[index+1][1]), (0 + dp[index+1][0]));
}
dp[index][buy] = profit;
}
}
return dp[0][1];
}
int solveSpace(vector<int>& prices){
vector<int> curr(2, 0);
vector<int> next(2, 0);
for(int index = prices.size()-1; index >= 0; index--){
for(int buy = 0; buy <= 1; buy++){
int profit = 0;
if(buy){
profit = max((-prices[index] + next[0]), (0 + next[1]));
}
else{
profit = max((prices[index] + next[1]), (0 + next[0]));
}
curr[buy] = profit;
}
next = curr;
}
return curr[1];
}
int maxProfit(vector<int>& prices) {
// vector<vector<int>> dp (prices.size(), vector<int>(2, -1));
// return solve(0, 1, prices, dp);
// return solveTab(prices);
return solveSpace(prices);
}
};