Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an integer array prices where prices[i] is the price of a given stock on the ith 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 (i.e., you must sell the stock before you buy again).
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), profit = 4-2 = 2.
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), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Constraints:
1 <= k <= 1001 <= prices.length <= 10000 <= prices[i] <= 1000Problem summary: You are given an integer array prices where prices[i] is the price of a given stock on the ith 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 (i.e., you must sell the stock before you buy again).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
2 [2,4,1]
2 [3,2,6,5,0,3]
best-time-to-buy-and-sell-stock)best-time-to-buy-and-sell-stock-ii)best-time-to-buy-and-sell-stock-iii)maximum-profit-from-trading-stocks)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #188: Best Time to Buy and Sell Stock IV
class Solution {
private Integer[][][] f;
private int[] prices;
private int n;
public int maxProfit(int k, int[] prices) {
n = prices.length;
this.prices = prices;
f = new Integer[n][k + 1][2];
return dfs(0, k, 0);
}
private int dfs(int i, int j, int k) {
if (i >= n) {
return 0;
}
if (f[i][j][k] != null) {
return f[i][j][k];
}
int ans = dfs(i + 1, j, k);
if (k > 0) {
ans = Math.max(ans, prices[i] + dfs(i + 1, j, 0));
} else if (j > 0) {
ans = Math.max(ans, -prices[i] + dfs(i + 1, j - 1, 1));
}
return f[i][j][k] = ans;
}
}
// Accepted solution for LeetCode #188: Best Time to Buy and Sell Stock IV
func maxProfit(k int, prices []int) int {
n := len(prices)
f := make([][][2]int, n)
for i := range f {
f[i] = make([][2]int, k+1)
for j := range f[i] {
f[i][j] = [2]int{-1, -1}
}
}
var dfs func(i, j, k int) int
dfs = func(i, j, k int) int {
if i >= n {
return 0
}
if f[i][j][k] != -1 {
return f[i][j][k]
}
ans := dfs(i+1, j, k)
if k > 0 {
ans = max(ans, prices[i]+dfs(i+1, j, 0))
} else if j > 0 {
ans = max(ans, -prices[i]+dfs(i+1, j-1, 1))
}
f[i][j][k] = ans
return ans
}
return dfs(0, k, 0)
}
# Accepted solution for LeetCode #188: Best Time to Buy and Sell Stock IV
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
@cache
def dfs(i: int, j: int, k: int) -> int:
if i >= len(prices):
return 0
ans = dfs(i + 1, j, k)
if k:
ans = max(ans, prices[i] + dfs(i + 1, j, 0))
elif j:
ans = max(ans, -prices[i] + dfs(i + 1, j - 1, 1))
return ans
return dfs(0, k, 0)
// Accepted solution for LeetCode #188: Best Time to Buy and Sell Stock IV
struct Solution;
impl Solution {
fn max_profit(k: i32, prices: Vec<i32>) -> i32 {
let n = prices.len();
let mut k = k as usize;
k = k.min(n / 2);
if k == 0 {
return 0;
}
let mut min_costs = vec![std::i32::MAX; k];
let mut max_profits = vec![0; k];
for price in prices {
min_costs[0] = min_costs[0].min(price);
max_profits[0] = max_profits[0].max(price - min_costs[0]);
for i in 1..k {
min_costs[i] = min_costs[i].min(price - max_profits[i - 1]);
max_profits[i] = max_profits[i].max(price - min_costs[i]);
}
}
max_profits[k - 1] as i32
}
}
#[test]
fn test() {
let prices = vec![2, 4, 1];
let k = 2;
let res = 2;
assert_eq!(Solution::max_profit(k, prices), res);
let prices = vec![3, 2, 6, 5, 0, 3];
let k = 2;
let res = 7;
assert_eq!(Solution::max_profit(k, prices), res);
}
// Accepted solution for LeetCode #188: Best Time to Buy and Sell Stock IV
function maxProfit(k: number, prices: number[]): number {
const n = prices.length;
const f = Array.from({ length: n }, () =>
Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => -1)),
);
const dfs = (i: number, j: number, k: number): number => {
if (i >= n) {
return 0;
}
if (f[i][j][k] !== -1) {
return f[i][j][k];
}
let ans = dfs(i + 1, j, k);
if (k) {
ans = Math.max(ans, prices[i] + dfs(i + 1, j, 0));
} else if (j) {
ans = Math.max(ans, -prices[i] + dfs(i + 1, j - 1, 1));
}
return (f[i][j][k] = ans);
};
return dfs(0, k, 0);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.