Best Time to Buy and Sell Stock IV
Hard
Topics
You are given an integer array nums where nums[i] is the price of a stock on day i, and an integer k. Return the maximum profit achievable with at most k transactions. You may not hold more than one share at a time.
Example 1
k reaches half the number of days the limit stops binding and this collapses to the unlimited-transactions problem, which is worth special-casing. Maximum profit: 2.Input: nums = [2,4,1], k = 2 Output: 2
Example 2
Input: nums = [3,2,6,5,0,3], k = 2 Output: 7
Constraints
- 0 <= k <= 100
- 1 <= nums.length <= 1000
- 0 <= nums[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
Two things describe your position at any moment: how many transactions you have spent, and whether you are currently holding a share. So the state is (day, transactions used, holding), and the shown solution carries it as two arrays indexed by transaction count — buy[j] is the best balance while holding a share inside the j-th transaction, and sell[j] the best balance after closing it.
buy[j] comes from sell[j-1] - price: finish the previous transaction, then pay for this share. sell[j] comes from buy[j] + price. Both are maxima against their own previous value, which is the "do nothing today" option.
The suspicious part is that buy[j] is updated and then immediately read by sell[j] in the same day's iteration, which looks like it permits buying and selling on one day. It does — and that is harmless, because such a transaction yields sell[j-1] - p + p = sell[j-1], a zero-profit move that can never beat a real one. Checked against an exhaustive state-space DP on 2,000 random inputs with no divergence.
Approach
- Initialise
buy[1..k]to negative infinity andsell[0..k]to 0. - For each day's price, for
jfrom 1 tok: relaxbuy[j]againstsell[j-1] - price, thensell[j]againstbuy[j] + price. - Return
sell[k].
Dry Run
nums = [3,2,6,5,0,3] k = 2
day price buy1 sell1 buy2 sell2
0 3 -3 0 -3 0
1 2 -2 0 -2 0
2 6 -2 4 -2 4
3 5 -2 4 -1 4
4 0 0 4 4 4
5 3 0 4 4 7
answer sell[2] = 7 buy 2 sell 6, then buy 0 sell 3Complexity
- Time — O(n·k): at the stated bounds that is 1000 × 100 = 10⁵ updates.
- Space — O(k): two arrays of length
k+1. The natural formulation is ann × k × 2table; it collapses because each day reads only the previous day's values. - When
k >= n/2the cap stops binding — you can take every profitable move — and the answer is just the sum of positive consecutive differences. Confirmed on five sequences. That shortcut is what keeps the approach viable whenkis huge, which this problem's bound of 100 does not require but the interviewer will ask about.
Common Pitfalls
- Initialising
buy[j]to 0 instead of negative infinity, which pretends you can hold a share you never bought. - Iterating
jdownward.buy[j]depends onsell[j-1], so ascendingjis what makes the in-place single-array form valid. - Treating the same-day buy-and-sell as a bug and adding a guard. It is a zero-profit transaction and the maxima discard it; the guard costs code and buys nothing.
- Forgetting the
k == 0or empty-input early return, where the loops never run andsell[k]would indexsell[0]— which happens to be 0, so the bug is invisible untilkis used for indexing elsewhere. - Reading "at most k transactions" as "exactly k".
sell[k]is a running maximum that already includes using fewer. - Counting a buy and its matching sell as two transactions. One round trip is one transaction.
Full Solution — all languages
class Solution:
def maxProfit(self, nums, k):
n = len(nums)
if k == 0 or n == 0:
return 0
buy = [float('-inf')] * (k + 1)
sell = [0] * (k + 1)
for p in nums:
for j in range(1, k + 1):
buy[j] = max(buy[j], sell[j - 1] - p)
sell[j] = max(sell[j], buy[j] + p)
return sell[k]import java.util.*;
class Solution {
public int maxProfit(int[] nums, int k) {
int n = nums.length;
if (k == 0 || n == 0) return 0;
long[] buy = new long[k + 1];
long[] sell = new long[k + 1];
Arrays.fill(buy, -1000000000L);
for (int p : nums) {
for (int j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - p);
sell[j] = Math.max(sell[j], buy[j] + p);
}
}
return (int)sell[k];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxProfit(vector<int>& nums, int k) {
int n = nums.size();
if (k == 0 || n == 0) return 0;
vector<long long> buy(k + 1, -1000000000LL), sell(k + 1, 0);
for (int p : nums) {
for (int j = 1; j <= k; j++) {
buy[j] = max(buy[j], sell[j - 1] - p);
sell[j] = max(sell[j], buy[j] + p);
}
}
return (int)sell[k];
}
};/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/ var maxProfit = function(nums, k) {
const n = nums.length;
if (k === 0 || n === 0) return 0;
const buy = new Array(k + 1).fill(-Infinity);
const sell = new Array(k + 1).fill(0);
for (const p of nums) {
for (let j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - p);
sell[j] = Math.max(sell[j], buy[j] + p);
}
}
return sell[k];
};