-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbest_time_to_buy_stock3.cpp
115 lines (100 loc) · 3.07 KB
/
best_time_to_buy_stock3.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
113
114
115
/*
problem link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
*/
#include <iostream>
#include <vector>
using namespace std;
class RecSolution
{
public:
int f(int day, bool canBuy, int cap, vector<int> &prices, int n)
{
if (day == n)
return 0;
if (cap == 0)
return 0;
int profit = 0;
if (canBuy)
{
int buy = -prices[day] + f(day + 1, 0, cap, prices, n);
int not_buy = 0 + f(day + 1, 1, cap, prices, n);
profit = max(buy, not_buy);
}
else
{
int sell = prices[day] + f(day + 1, 1, cap - 1, prices, n);
int not_sell = 0 + f(day + 1, 0, cap, prices, n);
profit = max(sell, not_sell);
}
return profit;
}
int maxProfit(vector<int> &prices)
{
int n = prices.size();
return f(0, 1, 2, prices, n);
}
};
class MemoSolution
{
public:
int f(int day, bool canBuy, int cap, vector<int> &prices, int n, vector<vector<vector<int>>> &dp)
{
if(day == n)
return 0;
if(cap == 0)
return 0;
if (dp[day][canBuy][cap] != -1)
return dp[day][canBuy][cap];
int profit = 0;
if(canBuy)
{
int buy = -prices[day] + f(day + 1, 0, cap, prices, n, dp);
int not_buy = 0 + f(day + 1, 1, cap, prices, n, dp);
dp[day][canBuy][cap] = max(buy, not_buy);
}
else
{
int sell = prices[day] + f(day + 1, 1, cap - 1, prices, n, dp);
int not_sell = 0 + f(day + 1, 0, cap, prices, n, dp);
dp[day][canBuy][cap] = max(sell, not_sell);
}
return dp[day][canBuy][cap];
}
int maxProfit(vector<int> &prices)
{
int n = prices.size();
// day, canbuy, cap
// n*2*3
vector<vector<vector<int>>> dp(n, vector<vector<int>>(2, vector<int>(3, -1)));
return f(0, 1, 2, prices, n, dp);
}
};
class Tabulation{
public:
int maxProfit(vector<int> &prices)
{
int n = prices.size();
// day, canbuy, cap
// n*2*3
vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(2, vector<int>(3, 0)));
for (int day = n - 1; day >= 0; day--)
for (int canBuy = 0; canBuy < 2; canBuy++)
for (int cap = 1; cap < 3; cap++)
{
if (canBuy)
{
// int buy = -prices[day] + f(day + 1, 0, cap, prices, n, dp);
int buy = -prices[day] + dp[day + 1][0][cap];
int not_buy = 0 + dp[day + 1][1][cap];
dp[day][canBuy][cap] = max(buy, not_buy);
}
else
{
int sell = prices[day] + dp[day + 1][1][cap - 1];
int not_sell = 0 + dp[day + 1][0][cap];
dp[day][canBuy][cap] = max(sell, not_sell);
}
}
return dp[0][1][2];
}
};