Best Time to Buy and Sell Stock IV - Problem
You're a stock trader with limited transactions - you can make at most k complete buy-sell cycles to maximize your profit.
Given an array prices where prices[i] represents the stock price on day i, and an integer k representing the maximum number of transactions allowed, find the maximum profit you can achieve.
Important constraints:
- You must sell before buying again (no simultaneous transactions)
- A transaction consists of buying AND then selling a stock
- You can complete at most
ktransactions
Example: If prices = [2,4,1] and k = 2, you can buy at 2, sell at 4 (profit = 2), but there's no profitable second transaction, so maximum profit is 2.
Input & Output
example_1.py — Basic Case
$
Input:
k = 2, prices = [2,4,1]
›
Output:
2
💡 Note:
Buy at price 2, sell at price 4. Profit = 4 - 2 = 2. No profitable second transaction possible.
example_2.py — Multiple Transactions
$
Input:
k = 2, prices = [3,2,6,5,0,3]
›
Output:
7
💡 Note:
Buy at price 2, sell at price 6 (profit = 4). Buy at price 0, sell at price 3 (profit = 3). Total = 7.
example_3.py — Edge Case
$
Input:
k = 2, prices = [1,2,3,4,5]
›
Output:
4
💡 Note:
One transaction is optimal: buy at 1, sell at 5 for profit of 4. Multiple smaller transactions don't yield more profit.
Constraints
- 0 ≤ k ≤ 100
- 0 ≤ prices.length ≤ 1000
- 0 ≤ prices[i] ≤ 1000
- Time limit: 2 seconds per test case
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code