LeetCode 123. Best Time to Buy and Sell Stock III
Question
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
1 | Input: prices = [3,3,5,0,0,3,1,4] |
Example 2:
1 | Input: prices = [1,2,3,4,5] |
Example 3:
1 | Input: prices = [7,6,4,3,1] |
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 105
Source: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
Solution
leftProfits[i]
means the max profit of all transactions in prices[:i]
(they can sell on day i or earlier). Similar for rightProfits[i]
.
The overlap point of day i for leftProfits[i]
and rightProfits[i]
is necessary. Because the question requires a result with at most two transactions. The overlap point can help two transactions to be merged into one.
We find seen min price and max price from two different ends to fill two cache arrays.
1 | public int maxProfit(int[] prices) { |
LeetCode 123. Best Time to Buy and Sell Stock III
http://yenotes.org/2022/01/18/LeetCode-123-Best-Time-to-Buy-and-Sell-Stock-III/