|
2 | 2 | import epi.test_framework.EpiTest; |
3 | 3 | import epi.test_framework.GenericTest; |
4 | 4 |
|
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.Arrays; |
5 | 7 | import java.util.List; |
| 8 | + |
6 | 9 | public class BuyAndSellStockTwice { |
7 | 10 | @EpiTest(testDataFile = "buy_and_sell_stock_twice.tsv") |
8 | 11 | 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; |
11 | 35 | } |
12 | 36 |
|
13 | 37 | public static void main(String[] args) { |
|
0 commit comments