Problem · Array
Maximum Stock Profit with Transaction Limits
Learn this problemProblem statement
Given daily stock prices prices and a transaction mode transactionLimit, return the maximum profit you can earn.
- When
transactionLimit == 1, complete at most one buy-then-sell transaction. - When
transactionLimit == -1, complete any number of nonoverlapping buy-then-sell transactions.
You may hold at most one share at a time. A sale must occur on a day after its matching purchase. You may always choose not to trade, so the answer is never negative.
Function
maxStockProfit(prices: int[], transactionLimit: int) → longExamples
Example 1
prices = [7,1,5,3,6,4]transactionLimit = -1return = 7Take the rises from 1 to 5 and from 3 to 6, for total profit 4 + 3 = 7.
Example 2
prices = [7,1,5,3,6,4]transactionLimit = 1return = 5The best single transaction buys at 1 and sells later at 6.
Example 3
prices = [7,6,4,3,1]transactionLimit = -1return = 0No later price exceeds an earlier purchase price, so skipping all trades is optimal.
Constraints
0 <= prices.length <= 200000.0 <= prices[i] <= 10^9.transactionLimitis either1or-1.- The answer fits a signed 64-bit integer.