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 k transactions

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
Best Time to Buy and Sell Stock IV INPUT Stock Prices Over Time 2 4 1 Day 0 Day 1 Day 2 Input Values: k = 2 (max transactions) prices = [2, 4, 1] 2 4 1 [0] [1] [2] ALGORITHM STEPS 1 Initialize DP Track buy/sell states buy[j] = -INF sell[j] = 0 2 Iterate Days For each price[i] 3 Update States For j = 1 to k: buy[j] = max(buy[j], sell[j-1]-p) sell[j] = max(sell[j], buy[j]+p) p = current price 4 Return Result sell[k] = max profit Trace: Buy@2, Sell@4 Profit = 4 - 2 = 2 Only 1 transaction needed FINAL RESULT Optimal Transaction BUY $2 Day 0 SELL $4 Day 1 -- Day 2 Profit Calculation 4 - 2 = 2 Maximum Profit 2 OK 1 of 2 trans used Key Insight: Use Dynamic Programming with O(k) space. Track two states per transaction: maximum profit after buying (holding stock) and after selling (not holding). Each day, update states in reverse order to avoid overwriting values needed for computation. Time: O(n*k), Space: O(k). TutorialsPoint - Best Time to Buy and Sell Stock IV | Optimal Solution (DP)
Asked in
Google 42 Amazon 38 Microsoft 31 Apple 24 Meta 19
89.3K Views
High Frequency
~35 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen