-
Notifications
You must be signed in to change notification settings - Fork 1
/
714. Best Time to Buy and Sell Stock with Transaction Fee.cpp
84 lines (67 loc) · 2.61 KB
/
714. Best Time to Buy and Sell Stock with Transaction Fee.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
/************************Method-1 (Bottom up approach, TC-O(N), SC-O(N)) ********************
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
vector<vector<int>> dp(n, vector<int>(2, 0));
// Base case
// 0 -> sell
// 1 -> buy
// When I will Buy I will pay fee
dp[n-1][0] = prices[n-1];
dp[n-1][1] = 0;
for(int i = n-2; i >= 0; i--) {
// SELL SELL NOW NOT SELL NOW
dp[i][0] = max(prices[i] + dp[i+1][1], dp[i+1][0]);
// BUY BUY NOW NOT BUY NOW
dp[i][1] = max(-prices[i] - fee + dp[i+1][0], dp[i+1][1]);
}
return dp[0][1];
}
};
***********************************************************************************************/
/************************Method-2 (Bottom up approach, TC-O(N), SC-O(1)) ********************
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
vector<vector<int>> dp(2, vector<int>(2, 0));
// Base case
// 0 -> sell
// 1 -> buy
// When I will Buy I will pay fee
dp[(n-1)%2][0] = prices[n-1];
dp[(n-1)%2][1] = 0;
for(int i = n-2; i >= 0; i--) {
// SELL SELL NOW NOT SELL NOW
dp[i%2][0] = max(prices[i] + dp[(i+1)%2][1], dp[(i+1)%2][0]);
// BUY BUY NOW NOT BUY NOW
dp[i%2][1] = max(-prices[i] -fee + dp[(i+1)%2][0], dp[(i+1)%2][1]);
}
return dp[0][1];
}
};
********************************************************************************************/
/**************** Method-3 (Bottom up approach, TC-O(N), SC-O(1)) - MORE SPACE OPTIMIZATION **************/
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size(), i;
vector<int> dp(2);
// Base case
// 0 -> sell
// 1 -> buy
// When I will Buy I will pay fee
dp[0] = prices[n-1];
dp[1] = 0;
int temp;
for(int i = n-2; i >= 0; i--) {
// SELL SELL NOW NOT SELL NOW
temp = max(prices[i] + dp[1], dp[0]);
// BUY BUY NOW NOT BUY NOW
dp[1] = max(-prices[i] -fee + dp[0], dp[1]);
dp[0] = temp;
}
return dp[1];
}
};