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
Understanding the Visualization
1
Initialize Trading Slots
Set up k transaction slots. Each has a 'buy state' (money after buying) and 'sell state' (profit after selling).
2
Process Daily Prices
For each day's price, update all trading slots optimally from highest to lowest transaction number.
3
Update Sell Decisions
For each slot, decide: keep previous sell profit or sell today (buy state + current price).
4
Update Buy Decisions
For each slot, decide: keep previous buy state or buy today (previous transaction's profit - current price).
5
Extract Maximum Profit
The sell state of the k-th transaction contains the maximum possible profit.
Key Takeaway
🎯 Key Insight: By maintaining separate buy/sell states for each transaction level and updating them optimally, we avoid exploring all combinations while guaranteeing the maximum profit.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code