Maximum Profit with Exactly Two Stock Transactions
Problem statement
Given daily stock prices, complete exactly two non-overlapping transactions. Each transaction buys once and sells on a later day, and the first sale must occur before the second purchase.
Return the maximum sum of the two profits. Both transactions are required, so either one may lose money.
Function
maxProfitExactlyTwo(prices: int[]) → intExamples
Example 1
prices = [3,3,5,0,0,3,1,4]return = 6Trade from 3 to 5, then from 0 to 4.
Example 2
prices = [7,6,4,3,1]return = -2Two required adjacent one-point losses are optimal.
Example 3
prices = [1,2,3,4]return = 2Use two one-point gains: 1 to 2 and 3 to 4.
Constraints
4 <= prices.length <= 100000.0 <= prices[i] <= 1000000.- The answer fits in a signed 32-bit integer.