Implement max profit with K transactions (DP)
Company: Citadel
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates dynamic programming, algorithmic optimization, and complexity-analysis skills by requiring a bottom-up DP implementation that maximizes stock trading profit with at most k transactions while returning optimal buy-sell pairs under tie-breaking constraints.
Read the full Citadel Data Scientist interview experience this question came from
Constraints
- 0 <= len(prices) <= 10000
- 0 <= k <= 100
- 0 <= prices[i] <= 10^9
- Transactions must satisfy buy_day < sell_day, and different transactions must be strictly disjoint in time.
Examples
Input: ([3, 2, 6, 5, 0, 3], 2)
Expected Output: (7, [(1, 2), (4, 5)])
Explanation: Buy on day 1 and sell on day 2 for profit 4, then buy on day 4 and sell on day 5 for profit 3. Total profit is 7.
Input: ([1, 3, 2, 0, 2], 2)
Expected Output: (4, [(0, 1), (3, 4)])
Explanation: The best two disjoint transactions are (0,1) for profit 2 and (3,4) for profit 2, totaling 4.
Hints
- Use exact-transaction DP states: cash[t] for the best profit after exactly t completed transactions and no stock in hand, and hold[t] for the best balance after opening transaction t.
- The O(n^2 k) version tries every earlier buy day for every sell day. You can avoid that by carrying forward the best value of cash[t-1] - prices[i] as you sweep from left to right.