Talentd
FleetCode
Make and follow sheets.Sign in

Difference Between Maximum and Minimum Price Sum solution and explanation

HardArrayDepth-First SearchDynamic ProgrammingTree6 min read34.5% acceptanceUpdated 9 Apr 2026
In Out DFS | Difference Between Maximum and Minimum Price Sum | Weekly Contest 328codingMohan · 36:54 · 3K viewsWatch on YouTube
9 more videos on this problem
  1. In Out DFS | Difference Between Maximum and Minimum Price Sum | Weekly Contest 328codingMohan · 36:54 · 3K views
  2. 2538. Difference Between Maximum and Minimum Price Sum | Weekly Contest 328 | LeetCode 2538Bro Coders · 14:23 · 3K views
  3. 【每日一题】LeetCode 2538. Difference Between Maximum and Minimum Price SumHuifeng Guan · 35:54 · 2K views
  4. 2538. Difference Between Maximum and Minimum Price Sum | LeetCode | C++Deep Tech · 13:10 · 1K views
  5. 2538. Difference Between Maximum and Minimum Price Sum (Leetcode Hard)Programming Live with Larry · 56:52 · 884 views
  6. Difference Between Maximum and Minimum Price Sum | Leetcode 2538 | Leetcode Weekly contest 328Tech Courses · 15:21 · 746 views
  7. LeetCode Weekly Contest 328 | 2538 : Difference Between Maximum and Minimum Price Sum SolutionFly with Coding | Newton School · 10:20 · 677 views
  8. 2538. Difference Between Maximum and Minimum Price Sum (Leetcode Solution in one dfs)Gaurav Singh · 19:06 · 346 views
  9. 2538. Difference Between Maximum and Minimum Price SumInterview Spinner · 25:21 · 147 views
  10. DSA SERIES | TREES #2 | 2538. Difference Between Maximum and Minimum Price Sum| 11.8.23CodingVerse · 17:58 · 137 views

The problem

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 <= 105
  • edges.length == n - 1
  • 0 <= ai, bi <= n - 1
  • edges represents a valid tree.
  • price.length == n
  • 1 <= price[i] <= 105

Approach overview

Problem Overview: You are given a tree where each node has a price. Choose any node as the root. From that root, consider all paths that start at the root and end at some node in the tree. The score for that root is the difference between the maximum path price sum and the minimum path price sum. The task is to compute the maximum possible score across all choices of root.

Approach 1: DFS Based Path Sum Calculation (O(n) time, O(n) space)

The key observation is that the difference between maximum and minimum path sums can be transformed into a tree dynamic programming problem. During a Depth-First Search, track two values for every node: the best path sum that must end at a leaf in its subtree and the best path sum that can end at any node. These states allow you to model the minimum and maximum path choices. While traversing children, combine subtree results and update a global answer representing the best possible difference. This approach processes each edge once, making it linear time.

Implementation builds an adjacency list for the tree, then runs a recursive DFS. Each recursive call returns the best downward sums for the current node. While merging results from different children, compute candidate differences by pairing paths that represent the minimum-side constraint (ending at a leaf) and the maximum-side freedom (ending anywhere). The algorithm is essentially a tree DP with two states per node.

Approach 2: Centroid Decomposition (O(n log n) time, O(n) space)

Centroid decomposition treats the tree as a hierarchy of balanced components. At each centroid, compute path sums from the centroid into each subtree using DFS. By aggregating subtree results and comparing maximum and minimum path contributions, you can evaluate candidate differences that pass through the centroid. After processing, remove the centroid and recursively process the remaining components.

This method is useful when problems involve path queries or combinations of paths across different subtrees. Each level of decomposition handles paths that pass through a particular centroid, ensuring no path is processed more than O(log n) times overall. Although more complex than the DFS DP approach, it generalizes well for many advanced tree path problems.

Recommended for interviews: The DFS-based tree dynamic programming solution. It runs in O(n) time, requires only one traversal, and demonstrates strong understanding of path aggregation in trees. Centroid decomposition is powerful but usually unnecessary unless the interviewer explicitly pushes toward advanced tree techniques.

Approach 1: DFS Based Path Sum Calculation

This approach involves using Depth-First Search (DFS) to traverse the tree and calculate the price sum paths for each node. The idea is to first perform a DFS from an arbitrary root to calculate the maximum path sum for each node as both the starting and ending node of a path. Using these precomputed values, the difference between maximum and minimum path sums can be computed efficiently by trying each node as a root one by one and tracking the possible maximum cost.

# Python Code for DFS Based Path Sum Calculation
/* Java Code for DFS Based Path Sum Calculation */
/* C++ Code for DFS Based Path Sum Calculation */
// JavaScript Code for DFS Based Path Sum Calculation
/* C Code for DFS Based Path Sum Calculation */
// C# Code for DFS Based Path Sum Calculation

Python's DFS approach first builds an adjacency list then uses two distinct DFS calls to first gather maximum possible length paths and then calculate costs for each node as root, akin to other languages. Each valid path is stored for further processing.

Complexity

Time Complexity: O(n), primarily limited by two DFS passes.
Space Complexity: O(n), due to recursion stacks and storage of path sums.

Try this approach in the editor

Approach 2: Centroid Decomposition

In this approach, centroid decomposition is employed for solving the problem more efficiently. The tree is considered recursively split at its centroid. This method helps efficiently calculate the price sums for paths without recalculating them from scratch for each potential root. In centroid decomposition, subproblems are solved and combined to achieve the global solution, and paths are calculated only once per component.

# Python Code for Centroid Decomposition
/* Java Code for Centroid Decomposition */
/* C++ Code for Centroid Decomposition */
// JavaScript Code for Centroid Decomposition
/* C Code for Centroid Decomposition */
// C# Code for Centroid Decomposition

Python applies centroid decomposition where the tree is systematically dismantled at centroids, allowing only necessary path sums to be calculated globally. By processing subproblems recursively, this solution bypasses complexity encountered with naive tree root permutations.

Complexity

Time Complexity: O(n log n), founded on centroid-driven recursive breaks.
Space Complexity: O(n), due to decomposition-level metadata and stack usage.

Try this approach in the editor

Approach 3: Default Approach

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)
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
DFS Based Path Sum Calculation

Time Complexity: O(n), primarily limited by two DFS passes.
Space Complexity: O(n), due to recursion stacks and storage of path sums.

Centroid Decomposition

Time Complexity: O(n log n), founded on centroid-driven recursive breaks.
Space Complexity: O(n), due to decomposition-level metadata and stack usage.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
DFS Based Path Sum CalculationO(n)O(n)Best general solution for trees; single DFS with tree DP states
Centroid DecompositionO(n log n)O(n)Useful for complex path aggregation problems or reusable centroid frameworks

Frequently asked questions

Is Difference Between Maximum and Minimum Price Sum easy or hard?

Difference Between Maximum and Minimum Price Sum is classified as Hard on LeetCode. The difficulty comes from designing the correct tree DP states and correctly combining subtree results during DFS traversal.

Difference Between Maximum and Minimum Price Sum Python/Java solution

Python and Java implementations typically build an adjacency list and run a recursive DFS that returns two DP values per node. The algorithm tracks maximum path sums and updates a global answer while combining results from children, achieving O(n) time complexity.

How to solve Difference Between Maximum and Minimum Price Sum in O(n)?

Build an adjacency list for the tree and perform a DFS. For every node, compute two DP values representing maximum downward path sums with different constraints. While merging child results, update the global maximum difference between path sums. Since each node is processed once, the algorithm runs in linear time.

What is the best approach for Difference Between Maximum and Minimum Price Sum?

The most efficient approach uses DFS with tree dynamic programming. During traversal, maintain two path states for each node: the best path that must end at a leaf and the best path that can end at any node. Combining these states while exploring children allows computing the maximum difference in O(n) time with O(n) space.

Is Difference Between Maximum and Minimum Price Sum asked at Google/Amazon/Meta?

Hard tree dynamic programming problems like this commonly appear in interviews at companies such as Google, Amazon, and Meta. The problem tests understanding of DFS, tree DP state design, and combining path results across subtrees.

What data structure is used in Difference Between Maximum and Minimum Price Sum?

The primary data structure is a tree represented using an adjacency list. The algorithm also relies on recursion with depth-first search and dynamic programming values stored per node during traversal.

What is the time complexity of Difference Between Maximum and Minimum Price Sum?

The optimal DFS-based solution runs in O(n) time where n is the number of nodes in the tree. Each node and edge is visited once during the traversal. Space complexity is O(n) due to the adjacency list and recursion stack used by the DFS.

Comments

Now write it yourselfClose this page and solve Difference Between Maximum and Minimum Price Sum in the editor, without looking.
Practise Difference Between Maximum and Minimum Price Sum