-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path188. Best Time to Buy and Sell Stock IV.cpp
70 lines (65 loc) · 2.06 KB
/
188. Best Time to Buy and Sell Stock IV.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
/**
50 min
WA: use original idea was wrong, greed got max interval.
change it to DP.
f[i][j], 1...i day, transaction j times.
1 3 4 2 5
k-1 k i
f[i][j] = max{f[i-1][j], max(f[k-1][j-1] + price[i]-price[k]) | k<i.}
O(n*n*K)
changed it to max(f[k-1][j-1]-price[k]) + price[i]
g[i][j]=max(f[k-1][j-1]-price[k]) | 0<=k<i
g[i-1][j]=max(f[k-1][j-1]-price[k]) | 0<=k<i-1
=max(f[i-2][j-1]-price[i-1], g[i-1][j]);
g[i][j] = max(f[i-2][j-1]-price[i-1], g[i-1][j]); // looks like money you earn - last cost.
f[i][j] = max{f[i-1][j],g[i][j]+price[i])
now it was O(n*k)
then, AC.
*/
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
vector<vector<int>> g(n, vector<int>(k+1, 0));
vector<vector<int>> f(n, vector<int>(k+1, 0));
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j <= k; j++) {
if (i >=2) {
g[i][j] = max(f[i-2][j-1] - prices[i-1], g[i-1][j]);
} else if (i == 1) {
g[i][j] = -prices[0];
}
if (i >= 1) {
f[i][j] = max(f[i-1][j], g[i][j] + prices[i]);
}
ans = max(ans, f[i][j]);
cout<<f[i][j]<<" ";
}
cout<<endl;
}
return ans;
}
int maxProfitWrong(int k, vector<int>& prices) { // wrong for [1,2,4,2,5,7,2,4,9,0]
int n = prices.size();
vector<int>oneOp;
int lastBuy = 0;
for(int i = 0; i < n; i++) {
if(i == n-1 || prices[i] > prices[i+1]) {
if (lastBuy < i) {
oneOp.push_back(prices[i] - prices[lastBuy]);
}
lastBuy = i+1;
}
}
for(auto op : oneOp) {
cout<<op<<endl;
}
sort(oneOp.begin(), oneOp.end(), greater<int>());
int ans = 0;
for (int i = 0; i<k && i < oneOp.size(); i++) {
ans += oneOp[i];
}
return ans;
}
};