-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbest_time_to_buy_stock2.cpp
112 lines (98 loc) · 2.63 KB
/
best_time_to_buy_stock2.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
problem link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
*/
#include <iostream>
#include <vector>
using namespace std;
class RecSolution
{
public:
int f(int idx, bool isBought, vector<int> &prices)
{
int profit = 0;
int n = prices.size();
if (idx == n)
return 0;
if (!isBought)
{
int buy = f(idx + 1, true, prices) - prices[idx];
int not_buy = f(idx + 1, false, prices) - 0;
profit = max(buy, not_buy);
}
else
{
int sell = f(idx + 1, false, prices) + prices[idx];
int not_sell = f(idx + 1, true, prices);
profit = max(sell, not_sell);
}
return profit;
}
int maxProfit(vector<int> &prices)
{
return f(0, false, prices);
}
};
class MemoSolution
{
public:
int f(int idx, bool isBought, vector<int> &prices, vector<vector<int>> &dp)
{
int profit = 0;
int n = prices.size();
if (idx == n)
return 0;
if (dp[idx][isBought] != -1)
return dp[idx][isBought];
if (!isBought)
{
int buy = f(idx + 1, true, prices, dp) - prices[idx];
int not_buy = f(idx + 1, false, prices, dp) - 0;
dp[idx][isBought] = max(buy, not_buy);
}
else
{
int sell = f(idx + 1, false, prices, dp) + prices[idx];
int not_sell = f(idx + 1, true, prices, dp);
dp[idx][isBought] = max(sell, not_sell);
}
return dp[idx][isBought];
}
int maxProfit(vector<int> &prices)
{
int n = prices.size();
vector<vector<int>> dp(n + 1, vector<int>(2, -1));
return f(0, false, prices, dp);
}
};
class TabulationSolution
{
public:
int maxProfit(vector<int> &prices)
{
int n = prices.size();
vector<vector<int>> dp(n + 1, vector<int>(2, 0));
dp[n][0] = 0;
dp[n][1] = 0;
for (int idx = n - 1; idx >= 0; idx--)
{
for (int b = 1; b >= 0; b--)
{
int profit = 0;
if (!b)
{
int buy = dp[idx + 1][1] - prices[idx];
int not_buy = dp[idx + 1][0] - 0;
profit = max(buy, not_buy);
}
else
{
int sell = dp[idx + 1][0] + prices[idx];
int not_sell = dp[idx + 1][1] + 0;
profit = max(sell, not_sell);
}
dp[idx][b] = profit;
}
}
return dp[0][0];
}
};