AlgoInsight

DSA problem

Best Time to Buy and Sell Stock IV

HardState Machine DPPattern: State Machine DPtop600AmazonMicrosoftGoogleBloombergCitadel

You are given an integer array prices where prices[i] is the price of a given stock on the i-th day, and an integer k. Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times. Note: You may not engage in multiple transactions simultaneously — you must sell the stock before you buy again.

This is the general form of the buy/sell family. When k = 1 the answer is the classic single-pass max-profit; when k = 2 it is Stock III; and as k grows toward n/2 the constraint becomes inactive — every profitable price climb can be captured because a transaction takes at least two days, so n / 2 transactions is the most that can ever be useful.

The straightforward DP defines dp[t][i][h] where t is the number of transactions used so far, i is the day, and h is whether we currently hold the stock (0 or 1). The transitions are: on day i with t transactions and not holding, either do nothing or buy (dp[t][i][1] candidate); when holding, either do nothing or sell (which finishes one transaction). A full table is O(n * k) cells with O(1) transitions, so O(n * k) total time and space.

The optimal implementation flattens the t dimension into two arrays of length k: buy[t] is the best profit after the t-th buy, and sell[t] is the best profit after the t-th sell. Each day updates them in order t = 1..k using the freshly improved sell[t-1] and buy[t] of the same day. A crucial shortcut: if 2 * k >= n the constraint cannot bite, so fall back to the unlimited-transaction greedy that sums all positive daily deltas. Final answer is sell[k] (or 0 if k = 0).

Examples

Example 1
Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4) for profit 2. No second transaction can improve on that because the remaining days only fall.
Example 2
Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6) for profit 4, then buy on day 5 (price = 0) and sell on day 6 (price = 3) for profit 3. Total profit is 7.
Example 3
Input: k = 3, prices = [1,2,3,4,5]
Output: 4
Explanation: Although three transactions are allowed, the prices are monotonic so the best is a single buy-low sell-high for profit 4. Extra transactions add nothing.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dynamic-programmingstate-machinearray

Browse all DSA problems