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.
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.
Time & Space Complexity
Time Complexity
O(n*k)
We process each of n prices and update k transaction states
โ Linear Growth
Space Complexity
O(k)
We only need to store buy and sell states for k transactions
โ Linear Space
Constraints
- 0 โค k โค 100
- 0 โค prices.length โค 1000
- 0 โค prices[i] โค 1000
- Time limit: 2 seconds per test case
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code