Problem Description
Given an array of stock prices where prices[i] is the price on the iᵗʰ day and an integer k, determine the maximum profit achievable with at most k transactions (a transaction is defined as one buy and one sell). Note that you cannot hold more than one stock at a time (i.e., you must sell before buying again).
Key Insights
- For a high value of k (k >= n/2 where n is the number of days), the problem reduces to the unlimited transactions case.
- When k is small, a dynamic programming approach is necessary to track the optimal profit at each transaction and day.
- Use a DP recurrence: dp[t][i] = max(dp[t][i-1], prices[i] + maxDiff), where maxDiff is updated as max(maxDiff, dp[t-1][i] - prices[i]).
- The idea is to iteratively build the solution for each transaction, using previously computed results efficiently.
Space and Time Complexity
Time Complexity: O(k * n) where n is the number of days. Space Complexity: O(k * n) for the DP table (can be optimized to O(n) per transaction if needed).
Solution
We use a dynamic programming solution. First, check if k is large enough to allow unlimited transactions. If yes, simply sum up all positive differences between consecutive days. Otherwise, create a 2D DP table where dp[t][i] represents the maximum profit using at most t transactions until day i. For each transaction from 1 to k and for each day we maintain a variable maxDiff representing the maximum value of (dp[t-1][j] - prices[j]) for j from 0 to the current day. This helps to update the dp state for a transaction with a sell on the current day using the optimal previous transaction state.