Stock Profit With One, Unlimited, or Two Trades
Problem statement
prices[i] is the price of one share on day i. A trade is buying one share on some day and selling it on a later day; its profit is the sell price minus the buy price. You can hold at most one share at a time, so a new trade can only start after the previous one is sold (selling and buying again on the same day is allowed).
Return three numbers, the largest total profit you can make with:
- at most one trade,
- any number of trades,
- at most two trades.
You may also make no trade at all, so each answer is at least 0. Return them as [oneTrade, anyNumber, twoTrades].
Function
stockProfits(prices: int[]) → int[]Examples
Example 1
prices = [4,9,2,5,1,8]return = [7,15,12]One trade: buy at 1 and sell at 8 for 7. Any number of trades: 4 to 9, 2 to 5 and 1 to 8 give 5 + 3 + 7 = 15. At most two trades: 4 to 9 and 1 to 8 give 5 + 7 = 12.
Example 2
prices = [8,6,3]return = [0,0,0]The price only falls, so every trade would lose money. Making no trade gives 0 in all three cases.
Example 3
prices = [1,3,2,6,4,7]return = [6,9,8]One trade: 1 to 7 for 6. Any number: 2 + 4 + 3 = 9. Two trades: 1 to 6 and 4 to 7 give 5 + 3 = 8, better than 1 to 3 and 2 to 7 (2 + 5 = 7).
Constraints
1 <= prices.length <= 10^40 <= prices[i] <= 10^4