Trains the technique from
LeetCode 3573Best Time to Buy and Sell Stock VThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
prices[i] is the quoted price of one freight slot on day i. You run a desk that may complete at most k trades over those days.
A trade uses two different days i < j and comes in one of two shapes:
i and hand it back on day j, for a gain of prices[j] - prices[i];i and cover the promise on day j, for a gain of prices[i] - prices[j].Only one trade may be open at a time, so a trade has to be closed before the next one opens. A new trade may open on the very same day the previous one closes. You may complete fewer than k trades, and completing none is allowed, in which case the total is 0.
Return the largest total gain you can finish with.
Example 1
One allowed pair of trades: a long taken on day 1 at 1 and handed back on day 2 at 9 gains 8, then a short promised on day 2 at 9 and covered on day 3 at 2 gains 7. The second trade opens on the day the first one closes, which the rules permit, and the total is 15.
Example 2
The one trade allowed is a short promised on day 0 at 9 and covered on day 1 at 4, which gains 9 - 4 = 5.
Example 3
Every quote is the same, so any trade in either direction gains 0. Completing no trades at all is allowed, so the total is 0.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def maximum_profit(prices: list[int], k: int) -> int:public long maximumProfit(int[] prices, int k)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.