|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=123 lang=java |
| 3 | + * |
| 4 | + * [123] Best Time to Buy and Sell Stock III |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Hard (32.90%) |
| 10 | + * Total Accepted: 138.3K |
| 11 | + * Total Submissions: 420.4K |
| 12 | + * Testcase Example: '[3,3,5,0,0,3,1,4]' |
| 13 | + * |
| 14 | + * Say you have an array for which the ith element is the price of a given |
| 15 | + * stock on day i. |
| 16 | + * |
| 17 | + * Design an algorithm to find the maximum profit. You may complete at most two |
| 18 | + * transactions. |
| 19 | + * |
| 20 | + * Note: You may not engage in multiple transactions at the same time (i.e., |
| 21 | + * you must sell the stock before you buy again). |
| 22 | + * |
| 23 | + * Example 1: |
| 24 | + * |
| 25 | + * |
| 26 | + * Input: [3,3,5,0,0,3,1,4] |
| 27 | + * Output: 6 |
| 28 | + * Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit |
| 29 | + * = 3-0 = 3. |
| 30 | + * Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = |
| 31 | + * 3. |
| 32 | + * |
| 33 | + * Example 2: |
| 34 | + * |
| 35 | + * |
| 36 | + * Input: [1,2,3,4,5] |
| 37 | + * Output: 4 |
| 38 | + * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit |
| 39 | + * = 5-1 = 4. |
| 40 | + * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you |
| 41 | + * are |
| 42 | + * engaging multiple transactions at the same time. You must sell before buying |
| 43 | + * again. |
| 44 | + * |
| 45 | + * |
| 46 | + * Example 3: |
| 47 | + * |
| 48 | + * |
| 49 | + * Input: [7,6,4,3,1] |
| 50 | + * Output: 0 |
| 51 | + * Explanation: In this case, no transaction is done, i.e. max profit = 0. |
| 52 | + * |
| 53 | + */ |
| 54 | +class Solution { |
| 55 | + public int maxProfit(int[] prices) { |
| 56 | + int buy1 = Integer.MIN_VALUE; // just buy 1nd stock |
| 57 | + int buy2 = Integer.MIN_VALUE; // just buy 2nd stock |
| 58 | + int sell1 = 0; // just have sold 1nd stock |
| 59 | + int sell2 = 0; // just have sold 2nd stock |
| 60 | + |
| 61 | + for (int price : prices) { |
| 62 | + sell2 = Math.max(sell2, buy2 + price); |
| 63 | + buy2 = Math.max(buy2, sell1 - price); |
| 64 | + sell1 = Math.max(sell1, buy1 + price); |
| 65 | + buy1 = Math.max(buy1, -price); |
| 66 | + } |
| 67 | + |
| 68 | + return sell2; |
| 69 | + } |
| 70 | +} |
| 71 | + |
0 commit comments