Skip to content

Commit 4e57127

Browse files
committed
5.7 Buy Sell Twice - Add textbook sol with O(n) space
1 parent d8af67c commit 4e57127

2 files changed

Lines changed: 27 additions & 3 deletions

File tree

epi_judge_java/epi/BuyAndSellStockTwice.java

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,36 @@
22
import epi.test_framework.EpiTest;
33
import epi.test_framework.GenericTest;
44

5+
import java.util.ArrayList;
6+
import java.util.Arrays;
57
import java.util.List;
8+
69
public class BuyAndSellStockTwice {
710
@EpiTest(testDataFile = "buy_and_sell_stock_twice.tsv")
811
public static double buyAndSellStockTwice(List<Double> prices) {
9-
// TODO - you fill in here.
10-
return 0.0;
12+
// Initial Attempt (textbook sol) - Alr. looked at the textbook lol
13+
// Using two (forward + backward) passes to compute two sets of profits
14+
// Time: O(n), Space: O(n)
15+
// Invariants:
16+
// - `firstProfits[i]` is always max. profit for prices[0:i]
17+
// - `maxP` at iteration i is always max. total profit for prices[i:]
18+
List<Double> firstProfits = new ArrayList<>(Arrays.asList(0.0));
19+
Double lowest = prices.get(0);
20+
21+
// Forward pass
22+
for (int i = 1; i < prices.size(); i++) {
23+
lowest = Math.min(lowest, prices.get(i));
24+
firstProfits.add(Math.max(firstProfits.get(i - 1), prices.get(i) - lowest));
25+
}
26+
27+
// Backward pass
28+
Double highest = Double.MIN_VALUE;
29+
Double maxP = 0.0;
30+
for (int i = prices.size() - 1; i >= 0; i--) {
31+
highest = Math.max(highest, prices.get(i));
32+
maxP = Math.max(maxP, highest - prices.get(i) + firstProfits.get(i));
33+
}
34+
return maxP;
1135
}
1236

1337
public static void main(String[] args) {

problem_mapping.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ problem_mapping = {
274274
"total": 402
275275
},
276276
"Java: BuyAndSellStockTwice.java": {
277-
"passed": 0,
277+
"passed": 402,
278278
"total": 402
279279
},
280280
"Python: buy_and_sell_stock_twice.py": {

0 commit comments

Comments
 (0)