-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathBestTimeToBuyAndSellStockIV.cpp
More file actions
79 lines (67 loc) · 2.31 KB
/
Copy pathBestTimeToBuyAndSellStockIV.cpp
File metadata and controls
79 lines (67 loc) · 2.31 KB
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
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if(n < 2) {
return 0;
}
vector<vector<int>> dp(k+1, vector<int>(n, 0)); // Space: O(KN)
// Time - O(K*N*N)
for(int i=1; i<=k; i++) {
for(int j=1; j<n; j++) {
dp[i][j] = max(dp[i][j-1], helper(i, j, dp, prices));
}
}
return dp[k][n-1];
}
// Profit by selling on current price (j)
// Profit = SP - BP
// For space optimized solution
// SP => price[j]
// BP => Effective Buy Price -> price[j] - previous profit (dp[k-1][j])
// Time - O(N)
int helper(int k, int x, vector<vector<int>> &dp, vector<int> &prices) {
int maxProfit = 0;
for(int i=0; i<x; i++) {
// Sell on day_x, buy on day_i and add profit from (i-1) transactions dp[k-1][i]
maxProfit = max(maxProfit, prices[x] - prices[i] + dp[k-1][i]);
}
return maxProfit;
}
};
// Time Complexity - O(K * N * N)
// Space Complexity - O(N * K)
// Method - 2
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if(n < 2) {
return 0;
}
vector<vector<int>> dp(k+1, vector<int>(n, 0)); // Space: O(KN)
// Time - O(K*N*N)
for(int i=1; i<=k; i++) {
int effectiveBuyPrice = prices[0];
for(int j=1; j<n; j++) {
dp[i][j] = max(dp[i][j-1], prices[j] - effectiveBuyPrice);
effectiveBuyPrice = min(effectiveBuyPrice, prices[j] - dp[i-1][j]);
}
}
return dp[k][n-1];
}
// Profit by selling on current price (j)
// Profit = SP - BP
// For space optimized solution
// SP => price[j]
// BP => Effective Buy Price -> price[j] - previous profit (dp[k-1][j])
// Time - O(N)
int helper(int k, int x, vector<vector<int>> &dp, vector<int> &prices) {
int maxProfit = 0;
for(int i=0; i<x; i++) {
// Sell on day_x, buy on day_i and add profit from (i-1) transactions dp[k-1][i]
maxProfit = max(maxProfit, prices[x] - prices[i] + dp[k-1][i]);
}
return maxProfit;
}
};