-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBestTimeToBuyAndSellStockII.java
More file actions
230 lines (209 loc) Β· 7.08 KB
/
BestTimeToBuyAndSellStockII.java
File metadata and controls
230 lines (209 loc) Β· 7.08 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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package Algorithms.DynamicProgramming;
/**
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 16 May 2025
*/
public class BestTimeToBuyAndSellStockII {
public static void main(String[] args) {
int[] prices = {7, 1, 5, 3, 6, 4};
System.out.println("maxProfitUsingTwoPointersMyApproach => " + maxProfitUsingTwoPointersMyApproach(prices));
System.out.println("maxProfitUsingBottomUpTabulationDp => " + maxProfitUsingBottomUpTabulationDp(prices));
System.out.println("maxProfitUsingTwoPointersEffectiveBuyPrice2 => " + maxProfitUsingTwoPointersEffectiveBuyPrice2(prices));
}
/**
* @TimeComplexity O(n)
* @SpaceComplexity O(1)
*
* This approach is same as {@link Algorithms.DynamicProgramming.BestTimeToBuyAndSellStock#maxProfitUsingTwoPointers(int[])}
* But here add profit instead of getting maxProfit
*/
public static int maxProfitUsingTwoPointersMyApproach(int[] prices) {
int profit=0, min=prices[0]; // l pointer
for(int i=1; i<prices.length; i++) { // r pointer
if(prices[i]<min) min=prices[i];
else {
profit += prices[i]-min;
min=prices[i];
}
}
return profit;
}
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++) {
// If today's price is higher than yesterday's, we take the profit
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
/**
* @TimeComplexity O(n)
* @SpaceComplexity O(1)
*
*
* EFFECTIVE BUY PRICE:
* --------------------
* EFFECTIVE BUY PRICE = Amount we invested from our pocket to buy stocks
*
* π₯ To calculate profit while using EBP approach
* we just do TotalProfit = (CurrSellAmount-EBP) β
* This TotalProfit is profit till now.
* So, no need to sum up profit in every sell, like we usually do i.e totalProfit+=profit β
*
* EXAMPLE:
* Buys and sell stocks in coins.
*
* Initially, we have lots of coins [c][c][c][c][c][c][c]...... in our pocket
*
* Eg: The stock market looks like [2, 5, 4, 6]
*
* Now buy 1st stock i.e price 2 == coins 2
*
* EXAMPLE WITH EXPLANATION 1
* [2, 5, 4, 6]
* ---------- "At Starting point, BUY == EFFECTIVE BUY PRICE" ----------
*
* EBP = π π
* BUY #1
* [c][c] ---> here we invested two coins from our pocket, the effective buy price is 2
* π π
*
* SELL #1
* [c][c][P1][P1][P1] ---> here we made profit of 3 coins
* π π π’ π’ π’
*
* PROFIT #1 = [P1][P1][P1]
* π’π’π’
*
*
*
* EBP = π
* BUY #2
* [P1][P1][P1][C] ---> we only invested one coin from our pocket --> the effective by price is 1, cause we invested the profit of 3 coins
* π’ π’ π’ π
*
* SELL #2
* [P1][P1][P1][C][P2][P2] ---> we made profit of 2 coins
* π’ π’ π’ π π’ π’
*
* PROFIT #2 = [P2][P2]
*
* TOTAL PROFIT = PROFIT #1 + PROFIT #2 = [P1][P1][P1][P2][P2] = 5
* π’ π’ π’ π’ π’
*
*
*
* SAME EXAMPLE WITH DIFFERENT EXPLANATION :
* [2, 5, 4, 6]
* ---------- "At Starting point, BUY == EFFECTIVE BUY PRICE" ----------
*
* EBP = π π
* BUY #1
* [c][c] ---> B1=2 or EBP=2
* π π
*
* SELL #1
* [c][c][P1][P1][P1] ---> S1=B1+P1=5
* π π π’ π’ π’
*
* PROFIT #1 = [P1][P1][P1] ---> P1=3
*
* TOTAL PROFIT = P = [P1][P1][P1] = S1-B1 = S1-EBP β
* π’ π’ π’
*
*
*
* EBP = π
* BUY #2
* [P1][P1][P1][C] ---> B2=4, B2=P1(3)+EBP(1) ---> EBP = B2-P1
* π’ π’ π’ π
*
* SELL #2
* [P1][P1][P1][C][P2][P2] ---> S2=B2+P2=6
* π’ π’ π’ π π’ π’
*
* PROFIT #2 = [P2][P2] ---> P2=2
*
* TOTAL PROFIT = P = [P1][P1][P1][P2][P2] = S2-(EBP) or S2-(B2-P1) β
* π’ π’ π’ π’ π’
*
* BUY #3
*
* Now, the total profit is P, EBP=B3-P -- i.e use TOTAL P β
* So, EBP can be -ve sometimes, which is also valid
*
* In below example maintain min & max to check whether we need to buy or sell stocks at i
*
* Here EBP and i are 2 pointers
*
* [2, 5, 4, 6]
*/
public static int maxProfitUsingTwoPointersEffectiveBuyPrice(int[] prices) {
int n = prices.length;
int profit = 0, effectiveBuyPrice = prices[0];
for (int i = 1; i < n; i++) {
// if sold curr stock, then "TotalProfit = currSellAmount-EBP"
// TP = S2-(EBP) or S2-(B2-P1)
profit = Math.max(profit, prices[i] - effectiveBuyPrice);
// if bought curr stock, then "EBP = currBuyPrice - TotalProfit"
// EBP = B2-P
effectiveBuyPrice = Math.min(effectiveBuyPrice, prices[i] - profit);
}
return profit;
}
/**
* While calculating EBP, price-TP --> what if price is smaller, we get -ve EBP right ?
* Yes, sometimes EBP can be -ve
* that means, TP is bigger & we didn't spend money from our pocket to buy that stock
*
* [7, 1, 5, 3, 6, 4]
* i
* here initially,
* price = 3,
* TP = 4,
* EBP = 1;
*
* Now, if we calculate
* EBP = price-TP = 3-4 = -1
* TP = price-EBP = 3-(-1) = 4
*
* So, finally this -ve EBP will balance back the TP
*/
public static int maxProfitUsingTwoPointersEffectiveBuyPrice2(int[] prices) {
int TP=0; // TotalProfit
int EBP=prices[0]; // EffectiveBuyPrice
for(int price: prices) {
TP = Math.max(TP, price-EBP);
EBP = Math.min(EBP, price-TP);
}
return TP;
}
public static int maxProfitUsingBottomUpTabulationDp(int[] prices) {
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return dp[n - 1][1];
}
public int maxProfitUsingBacktracking(int[] prices) {
int n = prices.length;
Integer[][] dp = new Integer[n][2];
return backtrack(prices,0,1,dp);
}
public int backtrack(int[] prices,int ind,int buy,Integer[][] dp) {
if(ind==prices.length)
return 0;
if(dp[ind][buy]!=null)
return dp[ind][buy];
int profit = 0;
if(buy==1) profit = Math.max(-prices[ind] + backtrack(prices,ind+1,0,dp),backtrack(prices,ind+1,1,dp));
else profit = Math.max(prices[ind] + backtrack(prices,ind+1,1,dp),backtrack(prices,ind+1,0,dp));
return dp[ind][buy] = profit;
}
}