Best Time to Buy and Sell Stock V - Problem
You are given an integer array prices where prices[i] is the price of a stock in dollars on the i-th day, and an integer k.
You are allowed to make at most k transactions, where each transaction can be either of the following:
- Normal transaction: Buy on day
i, then sell on a later dayjwherei < j. You profitprices[j] - prices[i]. - Short selling transaction: Sell on day
i, then buy back on a later dayjwherei < j. You profitprices[i] - prices[j].
Note that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.
Return the maximum total profit you can earn by making at most k transactions.
Input & Output
Example 1 — Basic Case with k=2
$
Input:
prices = [2,4,1,3], k = 2
›
Output:
5
💡 Note:
Best strategy: Buy at price 2, sell at 4 (profit +2), then short sell at 4, buy back at 1 (profit +3). Total profit = 2 + 3 = 5.
Example 2 — Single Transaction
$
Input:
prices = [3,1,4,2], k = 1
›
Output:
3
💡 Note:
One transaction: Buy at price 1, sell at price 4 for profit of 3. Alternatively, short sell at 3, buy back at 1 for same profit.
Example 3 — No Profit Possible
$
Input:
prices = [1,1,1,1], k = 2
›
Output:
0
💡 Note:
All prices are the same, so no profit can be made from any transaction.
Constraints
- 1 ≤ prices.length ≤ 1000
- 0 ≤ prices[i] ≤ 1000
- 0 ≤ k ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code