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 n, representing the number of employees in a company. Each employee is assigned a unique ID from 1 to n, and employee 1 is the CEO, is the direct or indirect boss of every employee. You are given two 1-based integer arrays, present and future, each of length n, where:
present[i] represents the current price at which the ith employee can buy a stock today.future[i] represents the expected price at which the ith employee can sell the stock tomorrow.The company's hierarchy is represented by a 2D integer array hierarchy, where hierarchy[i] = [ui, vi] means that employee ui is the direct boss of employee vi.
Additionally, you have an integer budget representing the total funds available for investment.
However, the company has a discount policy: if an employee's direct boss purchases their own stock, then the employee can buy their stock at half the original price (floor(present[v] / 2)).
Return the maximum profit that can be achieved without exceeding the given budget.
Note:
budget.Example 1:
Input: n = 2, present = [1,2], future = [4,3], hierarchy = [[1,2]], budget = 3
Output: 5
Explanation:
4 - 1 = 3.floor(2 / 2) = 1.3 - 1 = 2.1 + 1 = 2 <= budget. Thus, the maximum total profit achieved is 3 + 2 = 5.Example 2:
Input: n = 2, present = [3,4], future = [5,8], hierarchy = [[1,2]], budget = 4
Output: 4
Explanation:
8 - 4 = 4.Example 3:
Input: n = 3, present = [4,6,8], future = [7,9,11], hierarchy = [[1,2],[1,3]], budget = 10
Output: 10
Explanation:
7 - 4 = 3.floor(8 / 2) = 4 and earns a profit of 11 - 4 = 7.4 + 4 = 8 <= budget. Thus, the maximum total profit achieved is 3 + 7 = 10.Example 4:
Input: n = 3, present = [5,2,3], future = [8,5,6], hierarchy = [[1,2],[2,3]], budget = 7
Output: 12
Explanation:
8 - 5 = 3.floor(2 / 2) = 1 and earns a profit of 5 - 1 = 4.floor(3 / 2) = 1 and earns a profit of 6 - 1 = 5.5 + 1 + 1 = 7 <= budget. Thus, the maximum total profit achieved is 3 + 4 + 5 = 12.Constraints:
1 <= n <= 160present.length, future.length == n1 <= present[i], future[i] <= 50hierarchy.length == n - 1hierarchy[i] == [ui, vi]1 <= ui, vi <= nui != vi1 <= budget <= 160hierarchy is guaranteed to have no cycles.Problem summary: You are given an integer n, representing the number of employees in a company. Each employee is assigned a unique ID from 1 to n, and employee 1 is the CEO, is the direct or indirect boss of every employee. You are given two 1-based integer arrays, present and future, each of length n, where: present[i] represents the current price at which the ith employee can buy a stock today. future[i] represents the expected price at which the ith employee can sell the stock tomorrow. The company's hierarchy is represented by a 2D integer array hierarchy, where hierarchy[i] = [ui, vi] means that employee ui is the direct boss of employee vi. Additionally, you have an integer budget representing the total funds available for investment. However, the company has a discount policy: if an employee's direct boss purchases their own stock, then the employee can buy their stock at half the original price
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Tree
2 [1,2] [4,3] [[1,2]] 3
2 [3,4] [5,8] [[1,2]] 4
3 [4,6,8] [7,9,11] [[1,2],[1,3]] 10
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3562: Maximum Profit from Trading Stocks with Discounts
class Solution {
private List<Integer>[] g;
private int[] present;
private int[] future;
private int budget;
public int maxProfit(int n, int[] present, int[] future, int[][] hierarchy, int budget) {
this.present = present;
this.future = future;
this.budget = budget;
g = new ArrayList[n + 1];
Arrays.setAll(g, k -> new ArrayList<>());
for (int[] e : hierarchy) {
g[e[0]].add(e[1]);
}
return dfs(1)[budget][0];
}
private int[][] dfs(int u) {
int[][] nxt = new int[budget + 1][2];
for (int v : g[u]) {
int[][] fv = dfs(v);
for (int j = budget; j >= 0; j--) {
for (int jv = 0; jv <= j; jv++) {
for (int pre = 0; pre < 2; pre++) {
int val = nxt[j - jv][pre] + fv[jv][pre];
if (val > nxt[j][pre]) {
nxt[j][pre] = val;
}
}
}
}
}
int[][] f = new int[budget + 1][2];
int price = future[u - 1];
for (int j = 0; j <= budget; j++) {
for (int pre = 0; pre < 2; pre++) {
int cost = present[u - 1] / (pre + 1);
if (j >= cost) {
f[j][pre] = Math.max(nxt[j][0], nxt[j - cost][1] + (price - cost));
} else {
f[j][pre] = nxt[j][0];
}
}
}
return f;
}
}
// Accepted solution for LeetCode #3562: Maximum Profit from Trading Stocks with Discounts
func maxProfit(n int, present []int, future []int, hierarchy [][]int, budget int) int {
g := make([][]int, n+1)
for _, e := range hierarchy {
u, v := e[0], e[1]
g[u] = append(g[u], v)
}
var dfs func(u int) [][2]int
dfs = func(u int) [][2]int {
nxt := make([][2]int, budget+1)
for _, v := range g[u] {
fv := dfs(v)
for j := budget; j >= 0; j-- {
for jv := 0; jv <= j; jv++ {
for pre := 0; pre < 2; pre++ {
nxt[j][pre] = max(nxt[j][pre], nxt[j-jv][pre]+fv[jv][pre])
}
}
}
}
f := make([][2]int, budget+1)
price := future[u-1]
for j := 0; j <= budget; j++ {
for pre := 0; pre < 2; pre++ {
cost := present[u-1] / (pre + 1)
if j >= cost {
buyProfit := nxt[j-cost][1] + (price - cost)
f[j][pre] = max(nxt[j][0], buyProfit)
} else {
f[j][pre] = nxt[j][0]
}
}
}
return f
}
return dfs(1)[budget][0]
}
# Accepted solution for LeetCode #3562: Maximum Profit from Trading Stocks with Discounts
class Solution:
def maxProfit(
self,
n: int,
present: List[int],
future: List[int],
hierarchy: List[List[int]],
budget: int,
) -> int:
max = lambda a, b: a if a > b else b
g = [[] for _ in range(n + 1)]
for u, v in hierarchy:
g[u].append(v)
def dfs(u: int):
nxt = [[0, 0] for _ in range(budget + 1)]
for v in g[u]:
fv = dfs(v)
for j in range(budget, -1, -1):
for jv in range(j + 1):
for pre in (0, 1):
val = nxt[j - jv][pre] + fv[jv][pre]
if val > nxt[j][pre]:
nxt[j][pre] = val
f = [[0, 0] for _ in range(budget + 1)]
price = future[u - 1]
for j in range(budget + 1):
for pre in (0, 1):
cost = present[u - 1] // (pre + 1)
if j >= cost:
f[j][pre] = max(nxt[j][0], nxt[j - cost][1] + (price - cost))
else:
f[j][pre] = nxt[j][0]
return f
return dfs(1)[budget][0]
// Accepted solution for LeetCode #3562: Maximum Profit from Trading Stocks with Discounts
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3562: Maximum Profit from Trading Stocks with Discounts
// class Solution {
// private List<Integer>[] g;
// private int[] present;
// private int[] future;
// private int budget;
//
// public int maxProfit(int n, int[] present, int[] future, int[][] hierarchy, int budget) {
// this.present = present;
// this.future = future;
// this.budget = budget;
//
// g = new ArrayList[n + 1];
// Arrays.setAll(g, k -> new ArrayList<>());
//
// for (int[] e : hierarchy) {
// g[e[0]].add(e[1]);
// }
//
// return dfs(1)[budget][0];
// }
//
// private int[][] dfs(int u) {
// int[][] nxt = new int[budget + 1][2];
//
// for (int v : g[u]) {
// int[][] fv = dfs(v);
// for (int j = budget; j >= 0; j--) {
// for (int jv = 0; jv <= j; jv++) {
// for (int pre = 0; pre < 2; pre++) {
// int val = nxt[j - jv][pre] + fv[jv][pre];
// if (val > nxt[j][pre]) {
// nxt[j][pre] = val;
// }
// }
// }
// }
// }
//
// int[][] f = new int[budget + 1][2];
// int price = future[u - 1];
//
// for (int j = 0; j <= budget; j++) {
// for (int pre = 0; pre < 2; pre++) {
// int cost = present[u - 1] / (pre + 1);
// if (j >= cost) {
// f[j][pre] = Math.max(nxt[j][0], nxt[j - cost][1] + (price - cost));
// } else {
// f[j][pre] = nxt[j][0];
// }
// }
// }
//
// return f;
// }
// }
// Accepted solution for LeetCode #3562: Maximum Profit from Trading Stocks with Discounts
function maxProfit(
n: number,
present: number[],
future: number[],
hierarchy: number[][],
budget: number,
): number {
const g: number[][] = Array.from({ length: n + 1 }, () => []);
for (const [u, v] of hierarchy) {
g[u].push(v);
}
const dfs = (u: number): number[][] => {
const nxt: number[][] = Array.from({ length: budget + 1 }, () => [0, 0]);
for (const v of g[u]) {
const fv = dfs(v);
for (let j = budget; j >= 0; j--) {
for (let jv = 0; jv <= j; jv++) {
for (let pre = 0; pre < 2; pre++) {
nxt[j][pre] = Math.max(nxt[j][pre], nxt[j - jv][pre] + fv[jv][pre]);
}
}
}
}
const f: number[][] = Array.from({ length: budget + 1 }, () => [0, 0]);
const price = future[u - 1];
for (let j = 0; j <= budget; j++) {
for (let pre = 0; pre < 2; pre++) {
const cost = Math.floor(present[u - 1] / (pre + 1));
if (j >= cost) {
const profitIfBuy = nxt[j - cost][1] + (price - cost);
f[j][pre] = Math.max(nxt[j][0], profitIfBuy);
} else {
f[j][pre] = nxt[j][0];
}
}
}
return f;
};
return dfs(1)[budget][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.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.