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.
There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node.
The price sum of a given path is the sum of the prices of all nodes lying on that path.
The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root.
Return the maximum possible cost amongst all possible root choices.
Example 1:
Input: n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5] Output: 24 Explanation: The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31. - The second path contains the node [2] with the price [7]. The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost.
Example 2:
Input: n = 3, edges = [[0,1],[1,2]], price = [1,1,1] Output: 2 Explanation: The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3. - The second path contains node [0] with a price [1]. The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.
Constraints:
1 <= n <= 105edges.length == n - 10 <= ai, bi <= n - 1edges represents a valid tree.price.length == n1 <= price[i] <= 105Problem summary: There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node. The price sum of a given path is the sum of the prices of all nodes lying on that path. The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root. Return the maximum possible cost amongst all possible root choices.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Tree
6 [[0,1],[1,2],[1,3],[3,4],[3,5]] [9,8,7,6,10,5]
3 [[0,1],[1,2]] [1,1,1]
binary-tree-maximum-path-sum)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2538: Difference Between Maximum and Minimum Price Sum
class Solution {
private List<Integer>[] g;
private long ans;
private int[] price;
public long maxOutput(int n, int[][] edges, int[] price) {
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
this.price = price;
dfs(0, -1);
return ans;
}
private long[] dfs(int i, int fa) {
long a = price[i], b = 0;
for (int j : g[i]) {
if (j != fa) {
var e = dfs(j, i);
long c = e[0], d = e[1];
ans = Math.max(ans, Math.max(a + d, b + c));
a = Math.max(a, price[i] + c);
b = Math.max(b, price[i] + d);
}
}
return new long[] {a, b};
}
}
// Accepted solution for LeetCode #2538: Difference Between Maximum and Minimum Price Sum
func maxOutput(n int, edges [][]int, price []int) int64 {
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
type pair struct{ a, b int }
ans := 0
var dfs func(i, fa int) pair
dfs = func(i, fa int) pair {
a, b := price[i], 0
for _, j := range g[i] {
if j != fa {
e := dfs(j, i)
c, d := e.a, e.b
ans = max(ans, max(a+d, b+c))
a = max(a, price[i]+c)
b = max(b, price[i]+d)
}
}
return pair{a, b}
}
dfs(0, -1)
return int64(ans)
}
# Accepted solution for LeetCode #2538: Difference Between Maximum and Minimum Price Sum
class Solution:
def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:
def dfs(i, fa):
a, b = price[i], 0
for j in g[i]:
if j != fa:
c, d = dfs(j, i)
nonlocal ans
ans = max(ans, a + d, b + c)
a = max(a, price[i] + c)
b = max(b, price[i] + d)
return a, b
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
ans = 0
dfs(0, -1)
return ans
// Accepted solution for LeetCode #2538: Difference Between Maximum and Minimum Price Sum
// 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 #2538: Difference Between Maximum and Minimum Price Sum
// class Solution {
// private List<Integer>[] g;
// private long ans;
// private int[] price;
//
// public long maxOutput(int n, int[][] edges, int[] price) {
// g = new List[n];
// Arrays.setAll(g, k -> new ArrayList<>());
// for (var e : edges) {
// int a = e[0], b = e[1];
// g[a].add(b);
// g[b].add(a);
// }
// this.price = price;
// dfs(0, -1);
// return ans;
// }
//
// private long[] dfs(int i, int fa) {
// long a = price[i], b = 0;
// for (int j : g[i]) {
// if (j != fa) {
// var e = dfs(j, i);
// long c = e[0], d = e[1];
// ans = Math.max(ans, Math.max(a + d, b + c));
// a = Math.max(a, price[i] + c);
// b = Math.max(b, price[i] + d);
// }
// }
// return new long[] {a, b};
// }
// }
// Accepted solution for LeetCode #2538: Difference Between Maximum and Minimum Price Sum
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #2538: Difference Between Maximum and Minimum Price Sum
// class Solution {
// private List<Integer>[] g;
// private long ans;
// private int[] price;
//
// public long maxOutput(int n, int[][] edges, int[] price) {
// g = new List[n];
// Arrays.setAll(g, k -> new ArrayList<>());
// for (var e : edges) {
// int a = e[0], b = e[1];
// g[a].add(b);
// g[b].add(a);
// }
// this.price = price;
// dfs(0, -1);
// return ans;
// }
//
// private long[] dfs(int i, int fa) {
// long a = price[i], b = 0;
// for (int j : g[i]) {
// if (j != fa) {
// var e = dfs(j, i);
// long c = e[0], d = e[1];
// ans = Math.max(ans, Math.max(a + d, b + c));
// a = Math.max(a, price[i] + c);
// b = Math.max(b, price[i] + d);
// }
// }
// return new long[] {a, b};
// }
// }
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.